C语言中typedef
时间: 2024-01-12 11:22:57 浏览: 81
C语言中的typedef关键字用于为已有的数据类型创建一个新的名称。它的本质是做类型重命名。通过typedef,我们可以为基本数据类型、指针、数组、结构体等定义新的类型名称,使得代码更加易读和易维护。
以下是几个使用typedef的例子:
1. 为基本数据类型创建新的类型名称:
```c
typedef unsigned int u_int;
u_int x = 0;
```
在这个例子中,我们使用typedef为unsigned int创建了一个新的类型名称u_int。现在,我们可以使用u_int来声明变量,而不需要再写unsigned int。
2. 为指针创建新的类型名称:
```c
typedef int* int_p;
int_p p = NULL;
```
在这个例子中,我们使用typedef为int*创建了一个新的类型名称int_p。现在,我们可以使用int_p来声明指向int类型的指针变量。
3. 为数组创建新的类型名称:
```c
typedef int a[10];
a b;
```
在这个例子中,我们使用typedef为int[10]创建了一个新的类型名称a。现在,我们可以使用a来声明一个包含10个int元素的数组。
4. 为结构体创建新的类型名称:
```c
typedef struct stu {
char name[20];
int age;
} stu_t;
stu_t s;
```
在这个例子中,我们使用typedef为struct stu创建了一个新的类型名称stu_t。现在,我们可以使用stu_t来声明结构体变量。
阅读全文
相关推荐


















