【问题标题】:How do I assign to a void pointer in a structure another structure?如何将结构中的 void 指针分配给另一个结构?
【发布时间】:2013-03-04 15:52:00
【问题描述】:

在使用双向链接列表时我需要一些帮助,其中节点的结构包含指向 void 的指针。如果我定义了另一个结构,我想在其中插入节点的实际数据,我如何将它分配给指向 void 的指针?另外,如何打印列表?

我的节点结构,在头文件中定义:

typedef struct nodetype
{
    struct nodetype *prev, *next;
    void *data;
} NodeT;

我要在每个节点中插入的数据的结构,在 main.c 中定义:

typedef struct dataStructure
{
    int birthday;
    char *name;
}

【问题讨论】:

  • 您用于学习如何管理双向链表指针的参考文献没有关于如何分配内存或分配给指针的内容? 烧掉那本书。 旁注:您的dataStructure 类型定义不合法。没有与 typedef 关联的结束名称。但是,nodetype 看起来是正确的。
  • 我忘记在 dataStructure 定义中添加“struct”。我提供的参考资料很短而且不全面..

标签: c data-structures void-pointers doubly-linked-list


【解决方案1】:

你需要正确定义第二个typedef,例如

typedef struct dataStructure
{
    int birthday;
    char *name;
} dataStructure;

然后,一旦你分配/定义了结构,你可以像往常一样将第一种类型的指针设置为第二种:

dataStructure mydatastruct;
node->data = &mydatastruct;  //(void *) can point to anything

node->data = malloc(sizeof (dataStructure));  // direct allocation

如果您想通过节点结构访问数据结构的成员,则需要将 void 指针转换为 (dataStructure *),例如

((dataStructure *)node->data)->birthday = 1980;

宏可以帮助减少丑陋。

如果您的节点结构只指向该数据结构,那么直接指向它会简单得多,而不是使用 void 指针。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-18
    • 2015-03-27
    • 2012-07-29
    • 1970-01-01
    相关资源
    最近更新 更多