title: Struct with array of structs of unknown size
body: <p>I've been trying to wrap my head around this the whole day...</p>
  
  <p>Basically, I have a struct called State that has a name and another one called StateMachine with a name, an array of states and total number of states added:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  typedef struct State {
    const char * name;
  
  } State;
  
  typedef struct StateMachine {
    const char * name;
  
    int total_states;
    State ** states;
  
  } StateMachine;
  
  StateMachine * create_state_machine(const char* name) {
    StateMachine * temp;
  
    temp = malloc(sizeof(struct StateMachine));
  
    if (temp == NULL) {
      exit(127);
    }
  
    temp-&gt;name = name;
    temp-&gt;total_states = 0;
  
    temp-&gt;states = malloc(sizeof(struct State));
    return temp;
  }
  
  void destroy_state_machine(StateMachine* state_machine) {
    free(state_machine);
  }
  
  State * add_state(StateMachine* state_machine, const char* name) {
    State * temp;
  
    temp = malloc(sizeof(struct State));
  
    if (temp == NULL) {
      exit(127);
    }
  
    temp-&gt;name = name;
  
    state_machine-&gt;states[state_machine-&gt;total_states]= temp;
    state_machine-&gt;total_states++;
  
    return temp;
  }
  
  int main(int argc, char **argv) {
  
    StateMachine * state_machine;
  
    State * init;
    State * foo;
    State * bar;
  
    state_machine = create_state_machine("My State Machine");
  
    init = add_state(state_machine, "Init");
    foo  = add_state(state_machine, "Foo");
    bar  = add_state(state_machine, "Bar");
  
    int i = 0;
  
    for(i; i&lt; state_machine-&gt;total_states; i++) {
      printf("--&gt; [%d] state: %s\n", i, state_machine-&gt;states[i]-&gt;name);
    }
  
  }
  </code></pre>
  
  <p>For some reason (read low C-fu / years of ruby/python/php) I'm unable to express the fact that states is an Array of State(s). The above code prints:</p>
  
  <pre><code>--&gt; [0] state: ~
  --&gt; [1] state: Foo
  --&gt; [2] state: Bar
  </code></pre>
  
  <p>What happened with the first state added?</p>
  
  <p>If I malloc the states array on the first state added (e.g. state_machine = malloc(sizeof(temp)); then I get the first value but not the second.</p>
  
  <p>Any advices?</p>
  
  <p>This is a C question. I'm using gcc 4.2.1 to compile the sample.</p>