如何在C中声明和初始化指向结构的指针数组?

时间:2010-04-15 01:14:55

标签: c null pointers malloc 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;
}

2 个答案:

答案 0 :(得分:12)

下面:

list_node_t **array[10] = {NULL};

你正在声明一个指向你的struct指针的10个指针的数组。你想要的是一个包含10个指针结构的数组:

list_node_t *array[10] = {NULL};

令人困惑,因为是的,array实际上是一个指向指针的指针,但是方括号表示法在C中抽象出来,因此您应该将array视为一个指针数组。

您也不需要在此行上使用取消引用运算符:

*array[0] =  (list_node_t*) malloc(sizeof(list_node_t));

因为C用括号表示法为你解除引用。所以它应该是:

array[0] =  (list_node_t*) malloc(sizeof(list_node_t));

答案 1 :(得分:2)

list_node_t **array[10] = {NULL};行是错误的 - 在这里你声明指向列表节点指针的指针数组。将其替换为:

list_node_t *array[10] = { NULL };

它应该有用。

相关问题