use*_*392 13 c malloc null pointers structure
我在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;
}
Run Code Online (Sandbox Code Playgroud)
Jer*_*ten 13
这里:
list_node_t **array[10] = {NULL};
Run Code Online (Sandbox Code Playgroud)
你正在声明一个指向你的struct指针的10个指针的数组.你想要的是一个包含10个指针的数组:
list_node_t *array[10] = {NULL};
Run Code Online (Sandbox Code Playgroud)
这是令人困惑的,因为是的,它array确实是一个指向指针的指针,但是方括号表示法在C中抽象出来,所以你应该把它想象array成一个指针数组.
您也不需要在此行上使用dereference运算符:
*array[0] = (list_node_t*) malloc(sizeof(list_node_t));
Run Code Online (Sandbox Code Playgroud)
因为C使用括号表示法为您解除引用.所以它应该是:
array[0] = (list_node_t*) malloc(sizeof(list_node_t));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
53237 次 |
| 最近记录: |