简体   繁体   English

结构X中的结构X?

[英]Struct X in Struct X?

this is probably really simple, but how can I get a struct x to be in struct x in C? 这可能很简单,但是如何在C中的struct x中得到一个struct x? So for example: 例如:

typedef struct _Node {
    Node node;
} Node;

I've done some research and tried using pointers, like this: 我做了一些研究并尝试使用指针,如下所示:

typedef struct _Node {
    struct Node *node;
} Node;

Although that leaves the variable node as a pointer, which I don't want, I just want it to be an instance of the Node struct. 虽然这会将变量节点作为指针(我不想要),但我只想让它成为Node结构的一个实例。 Thanks for any help. 谢谢你的帮助。 :) :)

EDIT: 编辑:

Essentially what I'm trying to do is: 基本上我要做的是:

Node current = createNode(...);
while (true) {
    Node node = createNode(..., &current);
    addToList(node);
    current = somethingElse();
}

As you can probably imagine, I want a regular node to go into the createNode() function: 你可以想象,我想要一个常规节点进入createNode()函数:

Node createNode(..., Node node) {}
typedef struct node {
    struct node node;
} node_s;

This would lead to an "infinite recursion". 这将导致“无限递归”。 In other words, its size would be infinite. 换句话说,它的大小将是无限的。 The compiler cannot answer this question: how much memory to allocate ? 编译器无法回答这个问题: 要分配多少内存 Therefore it will throw a diagnostic message. 因此它会抛出一条诊断信息。

That's why you have to use pointers to create self-referential types. 这就是为什么你必须使用指针来创建自引用类型。

typedef struct node {
    struct node *node;
} node_s;

By the way, identifiers starting with an underscore followed by an underscore or capital letter are reserved to the implementation. 顺便说一下,以下划线后跟下划线或大写字母开头的标识符保留给实现。

That isn't possible. 那是不可能的。 Because that comes under incomplete type. 因为那是不完整的类型。 No struct Node inside struct Node inside struct Node ...and so on.... That makes your original structure incomplete. 没有struct Node内部struct Node内部struct Node ...等等....这使得原来的结构不完整。 Hence incomplete type definition. 因此类型定义不完整。

The reason is that. 原因是。

  1. In order a field to be inside a structure, it has to be a known type. 为了使一个字段位于结构内部,它必须是已知类型。
  2. But by the time we see struct Node inside struct Node{} it isn't yet determined. 但是当我们在struct Node{}看到struct Node它尚未确定。
  3. It's only determined after scanning all definition of struct Node{} but that's only possible after knowing the type of struct Node inside which leads to a paradox . 它只是在扫描了struct Node{}所有定义之后才确定,但这只有在知道了struct Node的类型之后才有可能导致paradox

But the case is different if you include struct Node * . 但是,如果包含struct Node *则情况会有所不同。

  1. When you reach struct Node * , you know it's a pointer type. 当你到达struct Node * ,你知道它是一个指针类型。 That needs a fixed amount of storage no matter what the type of pointer is. 无论指针的类型是什么,都需要一定量的存储空间。
  2. So, it successfully scans it and finishes the definition of struct Node{} . 因此,它成功扫描并完成struct Node{}的定义。 Hence it's a complete type. 因此它是一个完整的类型。

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

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