typedef struct test {
int a;
};
int main(void) {
test t;
t.a = 3;
}
以上不编译。但是当我将结构更改为:
时typedef struct {
int a;
}test;
一切正常。为什么是这样?我已经看到了很多代码示例,其中struct与typedef在同一行,但它不是为我编译的。
答案 0 :(得分: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
参考: - this
答案 1 :(得分:2)
当您对结构使用typedef
时,typedef
名称将在结构后放置。这就是指定C的工作方式。
如果你使用第一个(显然没有typedef
),那么你必须使用struct
关键字,第二个你只需要使用名称。
您也可以为结构和typedef
之类的
typedef struct test {
int a;
} test;
答案 2 :(得分: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!) ;
您已经传递了第一个“param”,一个名为struct
的{{1}},但您从未使用第二个参数为此类型指定新名称。
我认为你想要的是:
test
现在你已经采用了一个包含单个字段(typedef struct { int a; } test;
)的结构,并将其命名为a
。