Rai*_*ain 6 c struct typedef declaration
我正在阅读'C编程语言',并遇到了关于struct的 typedef的问题.代码是这样的:
typedef struct tnode *Treeptr;
typedef struct tnode { /* the tree node: */
char *word; /* points to the text */
int count; /* number of occurrences */
struct tnode *left; /* left child */
struct tnode *right; /* right child */
} Treenode;
Run Code Online (Sandbox Code Playgroud)
到我们写的时候
typedef struct tnode *Treeptr;
Run Code Online (Sandbox Code Playgroud)
tnode仍未声明,但我们没有得到任何编译错误,但是当我们将上面的语句更改为:
typedef Treenode *Treeptr;
Run Code Online (Sandbox Code Playgroud)
我们得到编译错误:
error: parse error before '*' token
warning: data definition has no type or storage class
Run Code Online (Sandbox Code Playgroud)
是什么导致了差异?"struct tnode"与"Treenode"不一样吗?
在定义之前不能使用类型.
使用typedef struct tnode { ... } Treenode;声明,Treenode直到达到分号才定义类型.
情况typedef struct tnode *Treeptr;不同.这告诉编译器'有一个被调用的结构类型struct tnode,并且该类型Treeptr是指向struct tnode' 的指针的别名.在该声明的最后,struct tnode是一个不完整的类型.您可以创建指向不完整类型的指针,但不能创建不完整类型的变量(因此您可以定义Treeptr ptr1;或者struct tnode *ptr2;它们是相同的类型,但您无法定义struct tnode node;).
的身体struct tnode可以写成:
typedef struct tnode
{
char *word;
int count;
Treeptr left;
Treeptr right;
} Treenode;
Run Code Online (Sandbox Code Playgroud)
因为在定义结构之前是Treeptr类型的已知别名struct tnode *.您不能使用Treenode *left;因为Treenode在达到最终的分号之前不是已知的别名(粗略地说).