How to initialise a pointer to pointer struct in C?
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.
/* I think this is correctly allocating the memory for this 'array' of nodes */
if (... == NULL)
return NULL;
When array allocation fails you do not free List, but lose pointer to it. Rewrite it as:
/* I think this is correctly allocating the memory for this 'array' of nodes */
if ((n = (Node **)malloc(l->size * sizeof(Node))) == NULL) {
free(l);
return NULL;
}
So from my point of wiev correct code would be:
typedef struct node {
struct node *next;
MyDef *entry;
} Node;
typedef struct list {
Node *table; /* (!) single asterisk */
int size;
} List;
List *initialize(void)
{
List *l;
Node **n;
if ((l = (MList *)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 *)calloc(l->size, sizeof(Node))) == NULL)
{
free(l);
return NULL;
}
/* Now, how do I set MyDef *entry and Node *next to NULL for each of the 'array'? */
l->table = n;
return l;
}
Futhermore C99 allows you to make variable size structs, so you able to init struct like
typedef struct list {
int size;
Node table[0]
} List;
And allocate as many Node's in table as you want using malloc(sizeof(List) + sizeof(Node)*n);
First of all, it seems to me that you have an error in your code allocating the array: It should say sizeof(Node*)
rather than sizeof(Node)
as you want to allocate an array of pointers to Node not an array of Node objects.
Then you can iterate through the array list:
for ( unsigned i = 0; i < l->size; ++i )
{
Node* node = l->table[ i ];
node->entry = NULL;
node->next = NULL;
}
Another hint: You really should check your initialization function against possibilities of memory leaks.
精彩评论