struct是一种构造类型,它是由若干“成员”组成的。 每一个成员可以是一个基本数据类型或者又是一个构造类型。
定义结构变量的一般格式为:
struct 结构名
{
类型 变量名;
类型 变量名;
...
} 结构变量;
结构名是结构的标识符不是变量名。
注意:结构体变量名不能与结构体名重复;在定义结构体时,系统不会对其分配实际内存,只有定义结构体变量时,系统才会为其分配内存。
typedef是类型定义的意思。
常用格式为:
typedef struct 结构名
{
类型 变量名;
类型 变量名;
...
} 结构别名;
typedef struct 是为了方便使用这个结构体。
具体区别在于:
若struct node {}这样来定义结构体的话。在申请node的变量时,需要这样写:struct node n;
若用typedef,可以这样写,typedef struct node{}NODE; 在申请变量时就可以这样:NODE n;
下面分三块来讲述:
1.首先
在C中定义一个结构体类型要用typedef:
typedef struct Student
{
int a;
}Stu;
于是在声明变量的时候就可:Stu stu1;
如果没有typedef就必须用struct Student stu1;来声明
这里的Stu实际上就是struct Student的别名。
另外这里也可以不写Student(于是也不能struct Student stu1了)
typedef struct
{
int a;
}Stu;
2.其次
struct Student
{
int a;
}stu1;//stu1是一个变量
typedef struct Student2
{
int a;
}stu2;//stu2是一个结构体类型
使用时可以直接访问stu1.a
但是stu2则必须先 stu2 s2;
然后 s2.a=10;
3.最后
如果在c程序中我们写:
typedef struct
{
int num;
int age;
}aaa,bbb,ccc;
相当于如下:
typedef struct
{
int num;
int age;
}aaa;
typedef aaa bbb;
typedef aaa ccc;
用typedef关键字将枚举类型定义成别名,并利用该别名进行变量声明:
typedef enum workday
{
saturday,
sunday = 0,
monday,
tuesday,
wednesday,
thursday,
friday
} workday; //此处的workday为枚举型enum workday的别名
workday today, tomorrow; //变量today和tomorrow的类型为枚举型workday=enum workday;
也可以写:
typedef enum
{
saturday,
sunday = 0,
monday,
tuesday,
wednesday,
thursday,
friday
} workday;



