Note that there are some explanatory texts on larger screens.

plurals
  1. POC - Static array of structs with string member not properly initialised?
    text
    copied!<p>Alright, so here goes. I am trying to do a switch over a string value in C, as described <a href="https://stackoverflow.com/a/4014981/962603">here</a>. However, the array of structs does not seem be initialised properly. My (simplified) program looks as follows:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #define BADKEY -1 #define VALUE 1 #define OTHERVALUE 2 #define FOOVALUE 3 #define NREQKEYS (sizeof(lookuptable)/sizeof(symstruct_t)) typedef struct { char *key; int val; } symstruct_t; static symstruct_t lookuptable[] = { { "some value here", VALUE }, { "other value", OTHERVALUE }, { "yet another one", FOOVALUE } }; int main(void) { // Testing... int i; for (i = 0; i &lt; NREQKEYS; i++) { symstruct_t *sym = lookuptable + i * sizeof(symstruct_t); printf("%d: key = '%s', val = %d.\n", i, sym-&gt;key, sym-&gt;val); } } </code></pre> <p>Then, I compile the above program as follows (it is saved in <code>test.c</code> obviously), on Debian Jessie (currently testing). The version of gcc is <code>gcc version 4.7.2 (Debian 4.7.2-5)</code>. Compiling gives no warnings or errors.</p> <pre><code>gcc test.c -o test -std=gnu99 </code></pre> <p>Now, I would expect that this simple program simply prints out the values that I initialise the array with. However, the output is this:</p> <pre><code>$ ./test 0: key = 'some value here', val = 1. 1: key = '(null)', val = 0. 2: key = '(null)', val = 0. </code></pre> <p>The two possible causes I can think of are that either my loop is incorrect, which makes no sense to me, or that the initialisation somehow is wrong. However, searching this site and in general on Google did not help me. I am open to other solutions as well, but also interested in just <em>why</em> this does not work.</p> <p>Thanks!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload