如何在 C 中声明并初始化指向结构的指针数组?
我在 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;
}
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.
#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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这里:
您正在声明一个由 10 个指针组成的数组,这些指针指向您的结构体。你想要的是一个包含 10 个指向你的结构的指针的数组:
这很令人困惑,因为是的,
array
确实是一个指向指针的指针,但是方括号表示法在 C 中为你抽象了这一点,并且所以你应该将array
视为一个指针数组。您也不需要在这一行上使用取消引用运算符:
因为 C 使用括号符号为您取消引用它。所以应该是:
Here:
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:
It's confusing because yes,
array
really 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 ofarray
as just an array of pointers.You also don't need to use the dereference operator on this line:
Because C dereferences it for you with its bracket notation. So it should be:
list_node_t **array[10] = {NULL};
行是错误的 - 在这里您声明了指向列表节点的指针的指针数组。将其替换为:它应该可以工作。
The line
list_node_t **array[10] = {NULL};
is wrong - here you declare array of pointers to pointers to list nodes. Replace that with:and it should work.