结构体struct 和 typedef

1 typedef

作用:起别名

1.1 typedef 变量

typedef int A;
A x = 10;

int 起别名,为 A

1.2 typedef 结构体

typedef struct{
	...
}Student;

struct{ … } 起别名,为 Student
另:

  • 有typedef,定义变量:
    Student stu;
  • 无typedef,定义变量(加struct):
    struct Student stu;

2 结构体

2.1 定义

两种:

// (1)
typedef struct{
	...
}Student, *PStudent;

// (2)
typedef struct Student{			// 由于内容中有struct Student
	...
	struct Student *deskmate;		//与(1)区别
}Student;

2.2 使用

以上两种均一样

类型 定义变量 访问成员
结构型(定义1个) Student stu; stu.a
结构型(定义n个) Student stu[n]; stu[i].a
指针型(定义1个) Student *stu;
stu = (Student *)malloc(sizeof(Student));
stu->a 或 (*stu).a
指针型(定义n个) Student *stu;
stu = (Student *)malloc(n * sizeof(Student));
stu[i]->a 或 (*stu)[i].a

指针型中:PStudent pstu; 等价 Student *stu;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章