【发布时间】:2011-05-04 22:11:22
【问题描述】:
struct node{
struct node next;
int id;
}
给出“下一个字段有不完整的类型错误”。
这个结构有什么问题?
【问题讨论】:
标签: c struct linked-list field
struct node{
struct node next;
int id;
}
给出“下一个字段有不完整的类型错误”。
这个结构有什么问题?
【问题讨论】:
标签: c struct linked-list field
创建自引用数据类型时,需要使用指针来解决循环问题:
struct node;
struct node {
struct node * next;
int id;
}
...应该可以,但在使用时注意正确分配内存。
为什么是指针?考虑一下:struct 定义的意义在于,当您说node.id 时,编译器可以计算出要分配多少内存以及要访问哪些部分。如果您的node 结构包含另一个node 结构,编译器应该为给定的node 分配多少内存?
通过使用指针可以解决这个问题,因为编译器知道为指针分配多少空间。
【讨论】:
如果一个结构可以包含它自己类型的另一个实例,它的大小将是无限的。
这就是为什么它只能包含一个指针指向它自己的类型。
此外,在代码中,结构的大小是未知的,因此编译器无法知道为其保留多少空间。
【讨论】:
node。试试这个:
struct node;
struct node{
struct node *next;
int id;
};
【讨论】:
不完整类型的某些用法是错误的,例如当您尝试声明不完整类型的对象时。但是,您可以声明一个指向不完整类型的指针(例如)。在这种情况下,这正是这里所需要的:
struct node{
struct node *next;
int id;
};
【讨论】:
问题是,当编译器到达这一行时:
struct node{
struct node next; /* << this line */
编译器实际上并不知道struct node 是什么,因为你定义了struct node。
一般来说,您不能使用未定义或不完整的类型。
【讨论】:
struct 由于自引用性将是无限大的。解决方案是使用指针 (struct node *next)。 ;-)
为了工作,你应该写:
typedef struct _node{
struct _node* next;
int id;
}node;
【讨论】: