Skip to content

2.11.3 typedef定义新类型

2.11.3 typedef定义新类型

现在我们来介绍C语言的一个新的关键字——typedef

typedef的本质功能是"起别名"

你可以理解为起一个外号,这个外号更方便我们的使用

比如你们宿舍有个同学叫王木合,你们可能就会直接叫老王

在结构体中,typedef也可以发挥类似的作用,同时也可以让结构体被视为一种"新的数据类型"

除此之外,typedef在其他方面也有很多应用,大家可以自行了解

如果定义一个新的别名?

我下面起一个示例

typedef struct studentInfo
{
    char name[20];
    int id;
    char sex;
}info;

现在,info就是一个代表studentInfo的数据类型了

我么后续使用结构体,都不需要打struct作为前缀了

那么我们上一节的案例就会变成这样:

#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct info
{
    char name[20];
    int id;
    char sex;
}info;

int main()
{
    info* stu;
    stu = (info*) malloc(sizeof(info));

    int input;
    printf("请输入学生的学号:");
    scanf("%d", &input);
    stu->id = input;

    printf("\n请输入学生的姓名:");
    char name[20];
    scanf("%s", name);
    strcpy(stu->name, name);

    char sex;
    printf("\n请输入学生的性别:");
    getchar();  //吞掉上一次输入后按下回车键后留下的回车
    scanf("%c", &sex);
    stu->sex = sex;

    //输出
    printf("\n");

    printf("name:%s\n", stu->name);
    printf("id:%d\n", stu->id);
    printf("sex:%c\n", stu->sex);

    free(stu);

    return 0;
}

当然,这么做主要还是起一个方便的作用 在后续链表的章节里,我们会看到这个typedef有多方便