结构中动态分配的指针数组

时间:2012-04-22 03:27:19

标签: c pointers struct

我想做这样的事情。

typedef struct Test{
  int value;
  struct Test* parent;
  struct Test** children;
}Test;

所以我想要一个指向另一个父结构的节点。然后我想要一个指向子节点的动态分配数组。我的问题是我不知道这将如何在语法上起作用。

例如,

Test* first;
Test* second;
Test* third;
(*third).value = 1;
(*first).parent = second;
(*first).child[0] = third;
printf("%d\n",(*first).(*child[0]).value);

无法编译。我假设我需要用malloc做一些事情来为指针数组分配空间,但我不确定。此外,我不确定如何访问父目录和子目录的“值”。

1 个答案:

答案 0 :(得分:1)

编辑:我已经添加了一个ideone链接到最终为你实现所有概念。

对于这个答案的简洁性,我很抱歉,我希望它会告诉你如何正确地做到这一点。

Test* first = (Test *)malloc(sizeof(Test));  // malloc(sizeof(Test)) allocates enough memory to hold a Test struct
Test* second = (Test *)malloc(sizeof(Test));
first->value = 1; // -> is the proper way to dereference pointers in this situation (sorry wrong term? I am up late) but I suppose your style can work, it just gets a bit confusing IMO
first->*child = (Test *)malloc(intptr_t * number_of_children); // intptr_t will make sure you have the right size of a pointer, you could also use sizeof(Test *) instead. i.e. malloc(sizeof(Test *));
first->child[0] = second; // The array-style subscript is just more readable IMO
printf("%d\n",first->child[0]->value); // child[0]-> will handle the dereferencing in a nice way

但是我会告诉你一些让你的生活更轻松的伎俩

typedef Test* test_array;

// ...later, in the struct...
test_array* child;

// ...later, in the malloc place...

first->child = (test_array *)malloc(sizeof(test_array *) * number_of_children);

其他一切都保持不变,你只需要更容易理解语法IMO。帮助处理那些棘手的双星。

编辑:这是链接 - http://ideone.com/TvSSB