我有一个简单的 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;
}
array
并不是 "真正的指向指针"。array
实际上是一个数组,而不是任何类型的指针。当表达式中使用数组类型时,会将其评估为指向数组第一个元素的指针,但数组仍然是一种实际的类型,与指针不同。sizeof array
应该有助于让你相信array
不是指针。 - cafarray[0] = (list_node_t*) malloc(sizeof(list_node_t));
改为array[0] = malloc(sizeof(list_node_t));
。 - James H