Struct with array of structs of unknown size

后端 未结 5 538
臣服心动
臣服心动 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:22

    You're doing a conceptual error:

    State ** states;
    

    It's true that you can consider states like an array of pointer to State object, but you are allocating space for just one state. When you do:

    state_machine->states[state_machine->total_states]= temp;
    

    you are doing something wrong if total_states is greater than zero because you are pointing to memory segments that are not been allocated (I'm wondering why you don't get a SEGFAULT). To store a dynamic number of State this way you need a linked list, or to call realloc every state you add(but that's not a good idea). The memory you are allocating with different malloc calls isn't continuous.

提交回复
热议问题