typedef

typedef existing new;

typedef 的功能是建立新的数据类型名,比如:

typedef int Length;  // 数据类型

typedef char *String;  // 字符指针

typedef struct tnode *Treeptr;  // 指针

typedef int (*PFI) (char *, char *); // 指向函数的指针

Length l = 120;
printf("%d \n", l);

typedef 声明并没有创建一个新类型,它只是为某个已存在的类型增加了一个新的名称而已。

使用 typedef 的两个关键好处是:

  • 可以使程序参数化,提高程序的移植性。
  • 可以为程序提供更好的说明性,增加可读性。

struct

struct 用于定义一个包含多个成员的新的数据类型。分别有以下 4 种定义方式:

方式 1:不指定类型名,直接声明结构体变量(不推荐使用)

struct {
    int age;
} student;

student.age = 18;
printf("%d \n", student.age);

方式 2:先定义类型名,再声明结构体变量

特点:每次都需要使用 struct 类型名 去声明变量。

struct Student {
    char name;
    int age;
};

struct Student student1;
student1.age = 20;

方式 3:定义类型名并声明结构体变量

struct HeadTeacher {
    int age;
} h1;

h1.age = 50;
struct HeadTeacher h2;
h2.age = 70;
printf("head teacher1 age = %d \n", h1.age);
printf("head teacher2 age = %d \n", h2.age);

方式 4:定义类型名并起别名 (推荐)

typedef struct {
    int age;
} Teacher;

Teacher t;
t.age = 30;
printf("teacher age = %d \n", t.age);