定义结构体

使用 struct 关键字定义结构体

  1. struct point {
  2. int x,y;
  3. }

以上定义了一个结构体类型 struct point ,包含了x、y两个int类型变量。

声明结构体变量

1 在定义结构体时,声明结构体变量

  1. struct point {
  2. int x,y;
  3. } first_point, second_point;

以上声明了类型 struct point 的两个变量 first_point 和 second_point;

指向结构体的指针变量声明:

  1. struct point {
  2. int x,y;
  3. } *my_point_ptr;

声明了结构体类型 struct point 的一个指针变量 my_point_ptr;

2 在定义结构体之后,声明结构体变量

  1. struct point {
  2. int x,y;
  3. };
  4. struct point first_point, second_point;
  5. // 声明该结构体的指针变量
  6. struct point *my_point_ptr;

以上同样声明了类型 struct point 的两个变量 first_point 和 second_point;

使用typedef定义结构体类型别名

typedef 语法为数据类型创建别名;语句结构

  1. typedef old-type-name new-type-name

1 给结构体类型 struct point 定义一个别名 point_type

  1. typedef struct point {
  2. int x, y;
  3. } point_type;

注意,这里的 point_type 是结构体 struct point 的别名,不是结构体 struct point 的变量;

示例

  1. typedef struct color {
  2. int x, y;
  3. } color_type;
  4. // 声明结构体类型color_type的一个变量my_color
  5. color_type my_color = {4,5};
  6. // 访问结构体成员
  7. printf("my_color.x=%d\n", my_color.x);
  8. // 声明结构体类型color_type的一个指针变量,并指向my_color
  9. color_type *my_color_ptr = &my_color;
  10. // 通过指针变量访问my_color的结构体成员
  11. printf("my_color_ptr->x=%d\n", my_color_ptr->x);

2 给结构体定义指针类型

  1. // 定义了结构体struct color的两种类型,结构体color_type和指向结构体的指针类型color_ptr_type
  2. typedef struct color {
  3. int x, y, z;
  4. } color_type, *color_ptr_type;
  5. // 声明变量并赋值
  6. color_type my_color;
  7. my_color.x = 10;
  8. color_ptr_type my_color_ptr;
  9. my_color_ptr = &color_type;
  10. printf("my_color.x=%d\n", my_color->x);
  11. printf("sizeof my_color %lu\n", sizeof(my_color));
  12. printf("sizeof my_color_ptr %lu\n", sizeof(*my_color_ptr));

上述示例展示了定义结构体指针类型;

  1. typedef struct color {
  2. int x, y, z;
  3. } *color_ptr_type;

参考:

  1. https://www.gnu.org/software/gnu-c-manual/gnu-c-manual.html#The-typedef-Statement