C语言中struct和typedef struct的区别

来源:互联网 发布:王者荣耀李白手办淘宝 编辑:程序博客网 时间:2024/05/09 13:03

最常见的一共有三种写法:

(1)
struct
{  int x;  int y;}test1;
(2)struct test{
   int x;   int y;}test1;
(3)typedef struct test{
   int x;   int y}text1,text2;

(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; typedef是取别名的意思
相当于把struct test 这种结构体取别名 叫 test1 或叫 test2

第一个:只定义了一个test1的结构体变量,以后还想定义这种结构体的话,必须重写整个结构体。第二个:以后想定义结构体的话,可以用struct test test2的方式定义。第三个:可以直接用text1 test3的形式定义结构体变量。

************************************************************************************************************************************

关于为什么要用第三种形式(即用typedef这种形式来定义结构体),可以看下面的解释:


其实这是为了简写的缘故,在ANSI C中你声明了一个
struct Piont
{
int x;
int y;
};

你在使用的时候,例如在声明Point的变量时,语法如下:
struct Piont p;
就是说你得带上这个关键字struct。
所以为了书写简单我们用
typedef struct Point
{
int x;
int y;
}Point ,*P;


这样声明了以后在程序中就可以直接使用Point p(表示定义一个Point类型的变量),

P ptr(表示定义一个Point类型的指针)了。


这种用法在ANSI C中经常用到。
但是在ANSI C++中,改进了这种语法,也就是说你声明一个Point变量时,可以不带关键字struct了。

0 0
原创粉丝点击