【问题标题】:Dynamically Allocated Array of Pointers in Struct结构中动态分配的指针数组
【发布时间】:2012-04-22 03:27:19
【问题描述】:

我想做这样的事情。

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

【问题讨论】:

    标签: c pointers struct


    【解决方案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

    【讨论】:

    • 谢谢,有帮助。虽然在这里它不会编译,除非我将调用转换为 malloc。在这种情况下我得到的错误是“错误:从‘void*’到‘Test* {aka main()::Test*}’[-fpermissive]的无效转换”
    • 添加演员表,让 malloc 开心
    • 还更新了 first->child 的 malloc。嗯,我来不及确定是first->child = (Test **) 还是first->*child = (Test *)。我认为我在这里的方式是正确的。双 * 很棘手。
    • @TomDavis 最后,添加了一种更容易管理双 * 的方法,我今晚出去了,投票给我,如果我回答了你,请给我一个答案:-P 或询问更多问题,我会在早上回答
    • @TomDavis grawr,双 * 是我的祸根,所以我以一种易于阅读的方式为您实现了它。检查链接。真的,睡吧。
    猜你喜欢
    • 2020-05-17
    • 1970-01-01
    • 1970-01-01
    • 2013-04-18
    • 2022-01-14
    • 1970-01-01
    • 2020-05-06
    • 1970-01-01
    • 2021-12-14
    相关资源
    最近更新 更多