【发布时间】:2011-02-08 04:26:45
【问题描述】:
我在 C 中有一个小任务。我正在尝试创建一个指向结构的指针数组。我的问题是如何将每个指针初始化为 NULL?此外,在为数组的成员分配内存后,我无法将值分配给数组元素指向的结构。
#include <stdio.h>
#include <stdlib.h>
typedef struct list_node list_node_t;
struct list_node
{
char *key;
int value;
list_node_t *next;
};
int main()
{
list_node_t *ptr = (list_node_t*) malloc(sizeof(list_node_t));
ptr->key = "Hello There";
ptr->value = 1;
ptr->next = NULL;
// Above works fine
// Below is erroneous
list_node_t **array[10] = {NULL};
*array[0] = (list_node_t*) malloc(sizeof(list_node_t));
array[0]->key = "Hello world!"; //request for member ‘key’ in something not a structure or union
array[0]->value = 22; //request for member ‘value’ in something not a structure or union
array[0]->next = NULL; //request for member ‘next’ in something not a structure or union
// Do something with the data at hand
// Deallocate memory using function free
return 0;
}
【问题讨论】:
标签: c null pointers malloc structure