Q:

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 :)

A:

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);

A:

The purpose of malloc (or calloc - which I prefer to use for structs) is to dynamically allocate the memory at runtime. So, your struct should look like this, since it is an object definition:
struct course {
    char identifier[2];
    int num_nodes;
    struct node *nodes;
};

Somewhere else in your program that uses the course struct, you will need to allocate memory (i) for any course objects you create and (ii) any node objects in that course.
e.g.
main()
{
   // lets say 1 course
   struct course *my_course;
   my_course = calloc(1, sizeof(struct course));

   // lets say 3 nodes in that course
   struct node *my_nodes;
   my_nodes = calloc(3, sizeof(struct node));

   my_course.num_nodes = 3;
   my_course.nodes = my_nodes;

   //...
   // clean up
   free(my_nodes);
   free(my_course);
}

Now, you are good. Make sure to free the memory before exiting.

