我有一个类似 -
的代码片段typedef struct {
int data;
struct abc *nxt; // Have not defined the structure of name "abc"
} mynode_t;
这里我没有定义名称“abc”的结构。这段代码仍然不会抛出错误并且可以正常编译。 谁能帮助理解这段代码如何正常工作?
请注意:代替“abc”,即使我给出其他名称,例如“xyz”,它也有效
因为语言允许这样做。它非常有用,允许像下面这样的构造:
struct Node {
struct Node* left;
struct Node* right;
}
它对于创建不透明类型也很有用。
请注意,取消引用
nxt
的代码将需要定义 struct abc
。
您没有使用此结构,您只是声明了对它的引用(指针)。它是合法的,但如果您尝试取消引用它或获取它的
sizeof
将产生错误,因为此结构声明不完整。
typedef struct {
int data;
struct abc *nxt; // Have not defined the structure of name "abc"
} mynode_t;
void foo(void)
{
mynode_t mn;
mn -> nxt = NULL; //OK
}
void bar(mynode_t *mn)
{
mn -> nxt -> something = 5; //wrong
}
void zoo(mynode_t *mn)
{
mn -> nxt = malloc(sizeof(*mn -> nxt)); //wrong
}