typedef用法详细讲解说明

typedef用于给一个数据类型创建一个别名

在基本数据类型中

#include

int main() {

int a = 1;

printf("%d\n", a);//1

typedef int zhangsan;

zhangsan b = 12;

printf("%d\n", b);//12

return 0;

}

在这个例子中,使用typedef后,int等价于zhangsan

在结构体中

不使用typedef:

#include

struct Student {

int id;//学号

char name[100];//姓名

char sex;

};

int main() {

struct Student st;

st.id = 1;

printf("%d\n", st.id);//1

struct Student* pst = &st;

//……

return 0;

}

使用typedef:

#include

typedef struct Student {

int id;//学号

char name[100];//姓名

char sex;

}SST;

int main() {

SST st;

st.id = 1;

printf("%d\n", st.id);//1

SST* pst = &st;

//……

return 0;

}

使用后,定义的结构体类型的名字struct Student可以用SST代替,二者等价

typedef struct Student {

int id;//学号

char name[100];//姓名

char sex;

}*PSST;

当typedef在结构体中这样使用的时候,PSST表示typedef struct Student*类型的变量,而不是typedef struct Student类型的。所以PSST类型的变量存放的是typedef struct Student类型的变量的地址。

typedef struct Student {

int id;//学号

char name[100];//姓名

char sex;

}*PSST,SST;

typedef可以像这样一块定义2个别名,这两个别名分别代表不同的含义。

其他

typedef还可以用于其他的,比如指针类型中,等等。用法都差不多。

你可能感兴趣的:(C语言学习笔记(入门到入神),算法,数据结构)