下一个结构项,不完整类型
struct node{
struct node next;
int id;
}
给出“下一个字段有不完整的类型错误”。
这个结构有什么问题?
struct node{
struct node next;
int id;
}
gives "field next has incomplete type error ".
what is wrong with this struct ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
创建自引用数据类型时,您需要使用指针来解决循环问题:
...应该可以,但在使用它时要注意正确分配内存。
为什么要有指针?考虑一下:
struct
定义的要点是,当您说出node.id
时,编译器可以计算出要分配多少内存以及要访问哪些部分。如果您的node
结构体包含另一个node
结构体,编译器应该为给定的node
分配多少内存?通过使用指针可以解决这个问题,因为编译器知道为指针分配多少空间。
When creating a self-referential data type, you need to use pointers to get around problems of circularity:
...should work, but take care to allocate memory correctly when using it.
Why a pointer? Consider this: the point of a
struct
definition is so that the compiler can figure out how much memory to allocate and what parts to access when you saynode.id
. If yournode
struct contains anothernode
struct, how much memory should the compiler allocate for a givennode
?By using a pointer you get around this, because the compiler knows how much space to allocate for a pointer.
如果一个结构体可以包含它自己类型的另一个实例,那么它的大小将是无限的。
这就是为什么它只能包含指向其自身类型的指针。
此外,在代码中,结构的大小是未知的,因此编译器无法知道要为其保留多少空间。
If a struct could contain another instance of its own type, its size would be infinite.
This is why it can only contain a pointer to its it own type.
Furthermore, at that point in code, the size of the struct is unknown, so the compiler couldn't know how much space to reserve for it.
试试这个:
node
yet while it's processing its definition.Try this:
不完整类型的某些使用是不正确的,例如当您尝试声明不完整类型的对象时。但是,您可以声明一个指向不完整类型的指针(例如)。在这种情况下,这正是这里所需要的:
Some uses of incomplete types are ill-formed, such as when you try to declare an object of an incomplete type. However, you can declare a pointer to an incomplete type (for example). In this case that is just what is needed here:
问题是,当编译器到达这一行时:
编译器实际上不知道什么是
struct node
,因为您正在定义struct node
。一般来说,不能使用未定义或不完整的类型。
The problem is, when the compiler reaches this line:
the compiler actually doesn't know what is
struct node
, because you're definingstruct node
.In general, you cannot use a type which is not defined or incomplete.
为了工作,你应该写:
In order to work, you should write: