2012-04-22 99 views
2

我想要做这样的事情。在结构中动态分配指针阵列

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

编辑:我已经添加了一个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

+0

谢谢,这有帮助。虽然在这里它不会编译,除非我把调用给malloc。我在这种情况下得到的错误是“错误:无效转换从'void *'到'测试* {aka main()::测试*}'[-fpermissive]” – 2012-04-22 03:51:29

+0

添加演员,让malloc很开心 – 2012-04-22 03:53:10

+0

也更新了第一个 - >孩子的malloc。嗯,我现在判断它应该是第一个 - >孩子=(测试**)还是第一个 - > *孩子=(测试*),为时已晚。我认为我在这里的方式是对的。双*是棘手的。 – 2012-04-22 03:55:58