编辑:我已经添加了一个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
谢谢,这有帮助。虽然在这里它不会编译,除非我把调用给malloc。我在这种情况下得到的错误是“错误:无效转换从'void *'到'测试* {aka main()::测试*}'[-fpermissive]” – 2012-04-22 03:51:29
添加演员,让malloc很开心 – 2012-04-22 03:53:10
也更新了第一个 - >孩子的malloc。嗯,我现在判断它应该是第一个 - >孩子=(测试**)还是第一个 - > *孩子=(测试*),为时已晚。我认为我在这里的方式是对的。双*是棘手的。 – 2012-04-22 03:55:58