I have a struct which is a node, and another which is a list of these nodes. In the list struct, its an array of nodes, but instead of an array, it’s a pointer to pointer with a size integer:
typedef struct node {
struct node *next;
MyDef *entry;
} Node;
typedef struct list {
Node **table;
int size;
} List;
List *initialize(void)
{
List *l;
Node **n;
if ((l = (List *)malloc(sizeof(List))) == NULL)
return NULL;
l->size = 11;
/* I think this is correctly allocating the memory for this 'array' of nodes */
if ((n = (Node **)malloc(l->size * sizeof(Node))) == NULL)
return NULL;
/* Now, how do I set MyDef *entry and Node *next to NULL for each of the 'array'? */
l->table = n;
return l;
}
How do I set MyDef *entry and Node *next to NULL for each of the ‘array’?
(Node **) is pointer to [array of] pointer to Node, so array you allocate will not have any struct members.
You should use (Node *) and then you’ll have pointed array of Node structs, or allocate each Node separately, then place pointers to them into your array.
There’s exist function calloc() in standard C library for your case: it inits allocated area with 0’s (which corresponds to (char/short/int/long)0, 0.0 and NULL).
Also there’s a memory leak.
When array allocation fails you do not free List, but lose pointer to it. Rewrite it as:
So from my point of wiev correct code would be:
Futhermore C99 allows you to make variable size structs, so you able to init struct like
And allocate as many Node’s in table as you want using
malloc(sizeof(List) + sizeof(Node)*n);