繁体   English   中英

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

[英]Dynamically Allocated Array of Pointers in 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做一些事情来为指针数组分配空间,但是我不确定。 另外,我不确定如何访问父目录和子目录的“值”。

编辑:我在末尾添加了一个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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM