关于 typedef struct 和 struct

来源:百度知道 编辑:UC知道 时间:2024/05/15 08:21:17
请高手帮忙解释以下几种结构体定义的区别:
struct{
int x;
int y;
}test1;

struct test
{int x;
int y;
}test1;

typedef struct test
{int x;
int y
}text1,text2;
这几种方法把小弟弄得头疼,不胜感激!
还有:
type struct
{int x;
int y;
}test1;

(1) struct{ int x; int y; }test1;
好,定义了 结构 test1,
test1.x 和 test1.y 可以在语句里用了。

(2) struct test {int x; int y; }test1;
好,定义了 结构 test1,
test1.x 和 test1.y 可以在语句里用了。
与 1 比,省写 了 test

(3)
typedef struct test
{int x; int y; // 你漏打分号,给你添上
}text1,text2;
只说了 这种结构 的(类型)别名 叫 text1 或叫 text2

真正在语句里用,还要写:
text1 test1;
然后好用 test1.x test1.y

或写 text2 test1;
然后好用 test1.x test1.y

(4)type struct {int x; int y; }test1;
这个不可以。
改 typedef ... 就可以了。
但也同 (3)一样,还要 写:
test1 my_st;
才能用 my_st.x 和 my_st.y

第一个:只定义了一个test1的结构体变量,以后还想定义这种结构体的话,必须重写整个结构体。

第二个:以后想定义结构体的话,可以用struct test test2的方式定义。

第三个:可以直接用text1 test3的形式定义结构体变量。

看了最佳答案,解释一下第三个

用 text1 或 text2 代替这一串:

struct test
{int x;
int y;
}

这时并没有定义一个结构体,但是接下来定义一个上面这样的结构体就可以写成这样:

text1 a;



text2 a;