Search code examples
c++crecursionstructfsm

Could you explain pointers and recursive structs


Could you explain what the pointers inside the structs mean? and how can recursive structure be useful? and could you please explain this code for me please? and how will it behave in the memory? Here is my C code:

struct State { 
unsigned long Out; 
unsigned long Time; //ms 
const struct State *Next[4];}; 

Solution

  • In this case, Next can hold 4 pointers to objects of the same type (struct State) in read-only addresses (4 non modifiable references).

    An example:

    #include <stdio.h>
    #include <stdlib.h>
    
    struct State { 
        unsigned long Out; 
        unsigned long Time; //ms 
        const struct State *Next[4];
    }; 
    
    void fn(struct State *data)
    {
        /* data->Next[0]->Out = 1; error: assignment of member ‘Out’ in read-only object */
        for (int i = 0; i < 4; i++) {
            printf("%ld %ld\n", data->Next[i]->Out, data->Next[i]->Time);
            free((struct State *)data->Next[i]); /* cast to non const */
        }
    }
    
    int main(void)
    {
        struct State data;
        struct State *next;
    
        for (int i = 0; i < 4; i++) {
            next = malloc(sizeof(*next));
            next->Out = i;
            next->Time = i * 10;
            data.Next[i] = next;
        }
        fn(&data);
        return 0;
    }