A link is a pointer to a node
typedef struct node * link;
In main(), I have the following code (config->m is just some integer):
// array of pointers to structs
link heads[config->m];
// make memory for head nodes
for(i = 0; i < config->m; i++)
heads[i] = malloc(sizeof(struct node));
The code works (which is great). But is there a way I can allocate config->m pieces of memory without the loop? I tried
link heads[config->m];
heads = malloc(sizeof(struct node) * config->m);
but my friendly neighborhood compiler tells me incompatible types in assignment
I know I could use
struct node heads[config->m];
But I want to do this stuff with pointers.
And as always, someone will ask me if this is part of homework, and the answer is yes (sort of). But this particular chunk of code doesn’t have anything to do with the actual assignment; it’s for my own enlightenment. But thanks for asking 😐
Nope, you need the loop. Your heads array is essentially a two dimensional array. You need at least two allocations. The first is the array of pointers:
The second is the memory that each member of the heads array points to:
And then to de-allocate: