为什么需要 typedef
在遇到一些自己定义的结构体啊这种名字很长的自定义变量类型时(系统定义变量类型也一样),可以利用这个 typedef() 去给它多起一个别名来简化,避免一直进行很复杂的名字的输入
怎么使用 typedef
方法一:在前面加一个声明
#include <stdio.h>
#include <string.h>
typedef struct Student ST;
struct Student
{
int sid;
char name[100];
int age;
char sex[100];
};
int main()
{
ST st;
st.sid = 201503010;
strcpy_s(st.sex, "male");
st.age = 23;
strcpy_s(st.name, "June");
printf("%d %s %d %s", st.sid, st.name, st.age, st.sex);
return 0;
}
201503010 June 23 male
方法二:定义结构体时直接使用
#include <stdio.h>
#include <string.h>
typedef struct Student
{
int sid;
char name[100];
int age;
char sex[100];
}ST;
int main()
{
ST st;
st.sid = 201503010;
strcpy_s(st.sex, "male");
st.age = 23;
strcpy_s(st.name, "June");
printf("%d %s %d %s", st.sid, st.name, st.age, st.sex);
return 0;
}
201503010 June 23 male
方法三:利用这个来直接重命名这个类型的指针
#include <stdio.h>
typedef struct Student
{
int sid;
char name[100];
int age;
char sex[100];
} * PST; // 等价于直接跳了一步定义出来一个struct Student *类型的数据类型
int main()
{
struct Student st;
PST ps = &st;
ps->sid = 201905;
printf("%d", ps->sid);
return 0;
}
201905
方法四:更进一步,既重命名那个类型,又重命名那个类型的指针
#include <stdio.h>
typedef struct Student
{
int sid;
char name[100];
int age;
char sex[100];
} *PST, ST; // 定义一个struct Student *类型的数据类型PST和struct Student类型的数据类型ST
int main()
{
ST st; // 等价于 struct Student st
PST ps = &st; // 等价于 struct Student * ps = &st
ps->sid = 201905;
printf("%d", ps->sid);
return 0;
}