Struct with array of structs of unknown size

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

    It looks like you want to have a variable number of states in each state machine, but you are allocating the memory incorrectly. In create_state_machine, this line:

    temp->states = malloc(sizeof(struct State));
    

    Allocates a single State object, not an array of pointers (which is how you are using it).

    There are two ways you could change this.

    1. Declare states as State states[]; but then you cant ever have more than a fixed number of states.
    2. Add another member to indicate how much storage has been allocated for states, so you can keep track of that as well as how much is used (which is what total_states is being used for).

    The later would look something like this:

    #include 
    #include 
    
    typedef struct 
    {
        const char *name;
    } State;
    
    typedef struct 
    {
        const char *name;
        int total_states;
        int states_capacity;
        State *states;
    } StateMachine;
    
    StateMachine *create_state_machine(const char *name)
    {
        StateMachine *temp = malloc(sizeof(StateMachine));
        memset(temp, 0, sizeof(*temp));
    
        temp->name = name;
        temp->states_capacity = 10;
        temp->states = malloc(sizeof(State) * temp->states_capacity);
    
        return temp;
    }
    
    State *add_state(StateMachine *machine, const char *name)
    {
        if (machine->total_states == machine->states_capacity)
        {
            // could grow in any fashion.  here i double the size, could leave
            // half the memory wasted though.
            machine->states_capacity *= 2;
    
            machine->states = realloc(
                machine->states, 
                sizeof(State) * machine->states_capacity);
        }
    
        State *state = (machine->states + machine->total_states);
        state->name = name;
    
        machine->total_states++;
    
        return state;
    }
    

提交回复
热议问题