Struct with array of structs of unknown size

后端 未结 5 526
臣服心动
臣服心动 2021-02-05 12:35

I\'ve been trying to wrap my head around this the whole day...

Basically, I have a struct called State that has a name and another one called StateMachine with a name, a

5条回答
  •  遥遥无期
    2021-02-05 13:28

    It looks like you're not allocating space for your states in the machine past the first one.

    StateMachine * create_state_machine(const char* name) {
      StateMachine * temp;
    
      temp = malloc(sizeof(struct StateMachine));
    
      if (temp == NULL) {
        exit(127);
      }
    
      temp->name = name;
      temp->total_states = 0;
    
      temp->states = malloc(sizeof(struct State)); // This bit here only allocates space for 1.
      return temp;
    }
    

    You're probably better off putting an array of states of fixed size in the state machine struct. If that's not okay, you'll have to realloc and move the whole set around or allocate chunks and keep track of the current length, or make a linked list.

    Incidentally, init, foo, and bar never get used.

    Edit: What I'm suggesting looks like this:

    #define MAX_STATES 128 // Pick something sensible.
    typedef struct StateMachine {
      const char * name;
      int total_states;
      State *states[MAX_STATES];
    } StateMachine;
    

提交回复
热议问题