typedef用法
用法1:给已知数据类型long起个新名字,叫byte_4。
typedef long byte_4;
用法2:在C中定义一个结构体类型的时候,
如果没有typedef,传统定义一个结构体:
struct Student
{
int no;
char name[12];
}Stu;
此时说明已经定义了一个结构体Stu变量,如果要重新新建,就必须使用struct Student stu1;。
如果要使用typedef:
typedef struct Student
{
int no;
char name[12];
}Stu, student;
在声明变量的时候可以用Stu stu1;或者student stu2;(Stu和student同时为Student的别名)。
用法3:如果使用了typedef,这里也可以不写Student,不能写struct Student stu1;了。
typedef struct
{
int no;
char name[12];
}Stu;
用法4:typedef可以掩饰复合类型,如指针和数组。
例如,你不用像下面这样重复定义有 81 个字符元素的数组:
char Line[81];
char text[81];
只需这样定义,Line类型即代表了具有81个元素的字符数组,使用方法如下:
typedef char Line[81];
Line text, line;
结构体指针用法
用法1:结构体要自引用时,Student1是错误用法。如果想引用成员next是另一个完整的结构,其内部还将包含它自己的成员next,这第二个成员又包含一个完整的结构,它还将包括它自己的成员next,这样重复下去,永无休止,内存都用完了,所以不合法。
struct Student
{
int age;
struct Student next;
}
正确的用法是:结构体自引用,只能自引用指针。编译器在结构的长度确定之前,就已经知道指针的长度,所以这种自引用是合法的。结构体的自引用在实现链表、树等高级的操作时作用很大。
struct Student
{
int age;
struct Student *next;
}
ps.这样是错误实例:
typedef struct
{
int age;
Student1 *next
}Student1, *StudentPtr;
虽然Student1代表了结构体,但是Student1类型名的声明是在末尾定义。当要声明struct{}的别名,内部无法识别Student1类型。
用法2:Student1是struct Student{}的别名,StudentPtr是Student的指针。
typedef struct Student
{
int age;
Student1 *next;
}Student1, *StudentPtr;
ps.
1.结构体指针需要初始化。
2.结构体指针的成员指针同样需要初始化。
3.若直接使用结构体,结构体中有成员指针,成员指针也需要初始化。