C语言 如何在 C 中声明和初始化指向结构的指针数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2642117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I declare and initialize an array of pointers to a structure in C?
提问by user246392
I have a small assignment in C. I am trying to create an array of pointers to a structure. My question is how can I initialize each pointer to NULL? Also, after I allocate memory for a member of the array, I can not assign values to the structure to which the array element points.
我在 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;
}
采纳答案by Jeremy Ruten
Here:
这里:
list_node_t **array[10] = {NULL};
You're declaring an array of 10 pointers to pointers to your struct. What you want is an array of 10 pointers to your struct:
您正在声明一个由 10 个指针组成的数组,这些指针指向指向您的结构的指针。你想要的是一个包含 10 个指向你的结构的指针的数组:
list_node_t *array[10] = {NULL};
It's confusing because yes, arrayreally is a pointer to a pointer, but the square bracket notation sort of abstracts that away for you in C, and so you should think of arrayas just an array of pointers.
这很令人困惑,因为是的,它array确实是一个指向指针的指针,但是方括号表示法在 C 中对您进行了抽象,因此您应该将其array视为只是一个指针数组。
You also don't need to use the dereference operator on this line:
您也不需要在这一行使用取消引用运算符:
*array[0] = (list_node_t*) malloc(sizeof(list_node_t));
Because C dereferences it for you with its bracket notation. So it should be:
因为 C 使用括号表示法为您取消引用它。所以应该是:
array[0] = (list_node_t*) malloc(sizeof(list_node_t));
回答by Nikolai Fetissov
The line list_node_t **array[10] = {NULL};is wrong - here you declare array of pointers to pointers to list nodes. Replace that with:
该行list_node_t **array[10] = {NULL};是错误的 - 在这里您声明指向列表节点的指针的指针数组。替换为:
list_node_t *array[10] = { NULL };
and it should work.
它应该工作。

