1
typedef struct test { 
    int a;
}; 

int main(void) { 
test t; 
t.a = 3; 
} 

以上不编译。但是,当我将结构更改为:

typedef struct {
    int a; 
}test; 

一切正常。为什么是这样?我已经看到很多代码示例,其中结构与 typedef 在同一行,但它没有为我编译。

4

3 回答 3

5

一般语法typedef

 typedef type-declaration      alias-name;
          |                     |
          |                     |
          |                     |
 typedef struct {int a; }      test; //2nd one is correct
          |                     |              
          |                     |
 typedef struct test { int a;}    ;  //You missed the synonym/alias name here

编辑

请参阅下面的 Eric Postpischil 评论

你会得到一个warning: useless storage class specifier in empty declaration

参考: -这个

于 2013-09-12T17:22:18.973 回答
2

typedef与结构一起使用时,typedef名称放在结构之后。这就是指定 C 工作的方式。

如果你使用第一个(typedef显然没有),那么你必须使用struct关键字,第二个你只需要使用名称。

您还可以对结构等使用相同的typedef名称

typedef struct test { 
    int a;
} test;
于 2013-09-12T17:23:12.240 回答
1

我将概念化typedef为有效地使用两个参数:

typedef "original type"  "new type";

(我知道这不是 100% 准确的,但为了简单起见,这是一种有用的查看方式)

如:

typedef unsigned int HRESULT;
// HRESULT is a new type that is the same as an unsigned int.

在您的示例中:

typedef struct test { int a; }  (Missing Second Parameter!) ;

你已经传递了第一个“参数”,一个structnamed test,但是你从来没有给这个类型一个带有第二个参数的新名称。

我想你想要的是:

typedef struct { int a; }  test;

现在您已经获取了一个带有单个字段 ( a) 的结构,并将其命名为test

于 2013-09-12T17:25:31.000 回答