在结构typedef声明规则 [英] Declaration rule in struct typedef

查看:164
本文介绍了在结构typedef声明规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在读C程序设计语言,并遇到一个问题有关的typedef 结构。在code是这样的:

I'm reading 'The C Programming Language' and encountered a problem about typedef of struct. The code is like this:

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;

这是我们写的时间

typedef struct tnode *Treeptr;

TNODE仍尚未宣布,但我们没有得到任何编译错误,
但是,当我们改变上面的语句为:

tnode is still not declared yet, but we don't get any compilation error, but when we change the statement above into:

typedef Treenode *Treeptr;

我们得到的编译错误:

error: parse error before '*' token
warning: data definition has no type or storage class

是什么原因导致的差异?是不是结构TNODE一样的树节点?

What causes the difference? Isn't "struct tnode" the same as "Treenode"?

推荐答案

您不能定义之前使用类型。

You can't use a type before it is defined.

随着 typedef结构TNODE {...}树节点; 声明中,键入树节点没有定义,直到到达分号。

With the typedef struct tnode { ... } Treenode; declaration, the type Treenode is not defined until the semi-colon is reached.

情况typedef结构TNODE * Treeptr; 是不同的。这告诉编译器有一个叫结构类型结构TNODE ,并键入 Treeptr 是一个指针的别名到结构TNODE 。在该声明中,结构TNODE 的结尾是一个不完整的类型。您可以创建指向不完全类型,但你不能创建不完全类型的变量(所以你可以定义 Treeptr ptr1的; 结构TNODE * PTR2; ,他们是同一类型,但你不能定义结构TNODE节点;

The situation with typedef struct tnode *Treeptr; is different. This tells the compiler 'there is a structure type called struct tnode, and the type Treeptr is an alias for a pointer to a struct tnode'. At the end of that declaration, struct tnode is an incomplete type. You can create pointers to incomplete types but you cannot create variables of the incomplete type (so you could define Treeptr ptr1; or struct tnode *ptr2; and they are the same type, but you could not define struct tnode node;).

正文中的结构TNODE 可以写成:

typedef struct tnode
{
    char    *word;
    int      count;
    Treeptr  left;
    Treeptr  right;
} Treenode;

由于 Treeptr 是该类型的已知别名结构TNODE * 前的结构定义。不能使用树节点*离开;是不是一个已知的别名,直到达到,因为树节点最后的分号(粗略地讲)。

because Treeptr is a known alias for the type struct tnode * before the structure is defined. You can't use Treenode *left; because Treenode is not a known alias until the final semi-colon is reached (roughly speaking).

这篇关于在结构typedef声明规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆