c - 为什么内部结构中不允许使用 typedef?

标签 c gcc struct typedef

我有一个在现有 typedef 结构中定义 typedef 结构的程序,我想知道为什么会出现编译错误。

程序如下:

typedef struct Outer
{
    typedef struct Inner
    {
        int b;
    }INNER;


    INNER inner;
    int a; 

}OUTER;

int main()
{ 
    OUTER obj;
    obj.a = 10;
    obj.inner.b=8;
    return 0;
}   

编译时出现以下错误::

test.c:3:5: error:expected specifier-qualifier-list before ‘typedef’
test.c: In function ‘main’:
test.c:17:5: error: ‘OUTER’ has no member named ‘a’
test.c:18:5: error: ‘OUTER’ has no member named ‘inner’  

但是,当我把程序改成

typedef struct Outer
{
    struct Inner
    {
        int b;
    };

    struct Inner inner;
    int a; 

 }OUTER;

 int main()
 {
    OUTER obj;
    obj.a = 10;
    obj.inner.b=8;
    return 0;
 }   

编译成功

为什么内部结构不允许使用 typedef?

最佳答案

C 不允许在结构成员的声明中使用存储类说明符(typedef,但也不允许使用 staticextern)。这在C99 6.7.2.1p1 的结构和 union 声明语法中有规定。

/* The compiler will issue a diagnostic for this declaration */ 
struct s {    
    static int a;
};

您可以将 6.7.2.1p1 语法与 6.7p1 中声明符不是函数参数或结构/union 成员的声明语法进行比较,并发现在这种情况下允许使用存储类说明符。

关于c - 为什么内部结构中不允许使用 typedef?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10984418/

相关文章:

unix - ar 在现有的 .a 文件上?

c++ - 为什么结构的 sizeof 不等于每个成员的 sizeof 之和?

c++ - 为什么结构的 sizeof 不等于每个成员的 sizeof 之和?

c - 添加到链接列表的末尾不起作用

使用 void 函数创建 POSIX 线程?

c - 使用 scanf 的格式错误的输出(黑客攻击 : The Art of Exploitation Example)

C 函数指针回调作为具有 "self"引用参数的结构成员

c - 如果 &a 生成 a 的地址,它如何成为指向 a 的指针?

python - 将基于 pygtk 的 C API 移植到 pygobject

c++ - 在特殊情况函数中展开 for 循环