Search code examples
carraysstructmallocdynamic-arrays

malloc array of structs in a struct


I have a struct called course and each course has multiple nodes (another struct 'node').

The number of nodes it has varies but I am given that number from a file that I am reading this information from, so that number sits in a variable.

So I need a malloc inside the struct. But I am confused. I know you can have arrays in structs but I don't know where to put the code that creates the malloc array since my struct is in my header file. Here's my code at the moment. I realize it looks wrong, I just don't know how I can fix it and where to initialize the malloc array.

struct course {
    char identifier[2];
    int num_nodes;
    struct node *nodes;
    nodes = (struct nodes*)malloc(num_nodes*sizeof(struct node));
};

struct node {
    int number;
    char type[2];
};

I want to be able to do something like:

struct node a_node;
struct course a_course;

a_course.nodes[0] = a_node;

etc...

I haven't used much C, this is the first time I've ever tried using dynamic arrays in C. My experience all comes from Java, and of course Java doesn't really use pointers in the same way as C so it's all a tad confusing for me.

So some help would be much appreciated, thanks a lot :)


Solution

  • The easiest approach is to create a function which initialises the struct:

    void init_course(struct course* c, const char* id, int num_nodes)
    {
        strncpy(c->identifier, id, sizeof(c->identifier));
        c->num_nodes = num_nodes;
        c->nodes = calloc(num_nodes, sizeof(struct node));
    }
    

    For symmetry, you could also then define a destructor

    void destroy_course(struct course* c)
    {
        free(c->nodes);
    }
    

    These would have usage like

    struct course c;
    init_course(&c, "AA", 5);
    /* do stuff with c */
    destroy_course(&c);