# 05-结构体及联合体

AI悦创原创C教程C教程大约 16 分钟...约 4907 字

## 1. 结构体 struct

### 1.1 结构体

``````// 课程结构体
struct course {
int id;                 // 课程 ID
char title[40];      // 课程名
float hours;        // 课程时长
};
``````

• 填空，声明结构体 `human`:
``````___human {
int age;
char name[40];
}
``````

struct

;

### 1.2 结构体变量的定义

Code
``````#include <stdio.h>

struct student {
int age;
char name[40];
};

int main() {
/* 声明结构体变量 */
struct student s1;
struct student s2;

s1.age = 19;
sprintf(s1.name, "John Bighimer");

s2.age = 22;
sprintf(s2.name, "Batman Jokerson");

printf("Student: %s, %d\n", s1.name, s1.age);
printf("Student: %s, %d\n", s2.name, s2.age);

return 0;
}
``````

1. 填空，声明一个结构体变量 `h1`:
``````struct human {
int age;
char name[40];
};
___ human h1;
``````

struct

### 1.3 声明结构体变量

``````#include <stdio.h>

struct student {
int age;
char name[40];
};

int main() {
/* declare two variables */
struct student s1 = {19, 9, "John Birghimer"};
struct student s2 = {22, 10, "Batman Jokerson"};

printf("Student: %s, %d\n", s1.name, s1.age);
printf("Student: %s, %d\n", s2.name, s2.age);

return 0;
}
``````

``````#include <stdio.h>

struct student {
int age;
char name[40];
};

int main() {
struct student s1; // 声明结构体变量

// 类型转换声明
s1= (struct student){19, 9, "John Birghimer"};

printf("Student: %s, %d\n", s1.name, s1.age);

return 0;
}
``````

``````#include <stdio.h>

struct student {
int age;
char name[40];
};

int main() {
struct student s1 = { .grade = 9, .age = 19, .name = "John Birghimer"};

return 0;
}
``````

• 填空，使用类型转换初始化 struct 变量 `h1`
``````struct human h1;
h1 = (___human) {19, "John"};
``````

### 1.4 结构体变量的引用

``````s1.age = 19;
``````

``````#include <stdio.h>

struct student {
int age;
char name[40];
};

int main() {
struct student s1 = {19, 9, "Jason"};
struct student s2;

printf("Assigning, s2 = s1\n");
s2 = s1;

return 0;
}
``````

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

struct course {
int id;
char title[40];
float hours;
};

int main() {
struct course cs1 = {341279, "Intro to C++", 12.5};
struct course cs2;

/* 初始化 cs2 */
cs2.id = 341281;
cs2.hours = 14.25;

/* 打印成员信息 */
printf("%d\t%s\t%4.2f\n", cs1.id, cs1.title, cs1.hours);
printf("%d\t%s\t%4.2f\n", cs2.id, cs2.title, cs2.hours);

return 0;
}
``````

• 填空，将变量 `h` 的年龄增加2岁：
``````struct human {
int age;      // 年龄
char name[40];
};
___human h1 = {19, "John"};
h1___age += 2;
``````

### 1.5 使用 typedef

typedef 关键字 创建一个类型定义，该定义可简化代码并使程序更易于阅读。

typedef 通常与结构体一起使用，因为它消除了在声明变量时使用关键字 struct 的需要。

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

typedef struct {
int id;
char title[40];
float hours;
} course;

int main() {
course cs1;
course cs2;

cs1.id = 123456;
strcpy(cs1.title, "JavaScript Basics");
cs1.hours = 12.30;

/* 初始化 cs2 */
cs2.id = 341281;
cs2.hours = 14.25;

/* 打印信息 */
printf("%d\t%s\t%4.2f\n", cs1.id, cs1.title, cs1.hours);
printf("%d\t%s\t%4.2f\n", cs2.id, cs2.title, cs2.hours);

return 0;
}
``````

• 填空，使用 typedef 关键字声明"human"结构":
``````___struct {
int age;
char name[40];
}___;
``````

## 2. 结构体的妙用

### 2.1 结构体中的结构

``````#include <stdio.h>

typedef struct {
int x;
int y;
} point;

typedef struct {
point center;
} circle;

int main() {
point p;
p.x = 3;
p.y = 4;

circle c;
c.center = p;

printf("Circle radius is %.2f, center is at (%d, %d)", c.radius, c.center.x, c.center.y);

return 0;
}
``````

``````#include <stdio.h>

typedef struct {
int x;
int y;
} point;

typedef struct {
point center;
} circle;

int main() {
circle c = {4.5, {1, 3}};
/* 4.5  1,3 */

return 0;
}
``````

• 填空，定义一个 `small` 结构体类型，并在结构体 `big` 中将成员变量 `s` 声明为 `small` 类型：
``````typedef ___{
float b;
} small;

struct big {
int a;
___s;
};
``````

### 2.2 结构体指针

``````struct myStruct *struct_ptr;
``````

``````struct_ptr = &struct_var;
``````

``````struct_ptr -> struct_mem;
``````

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

// Student 结构体定义
struct student{
char name[50];
int number;
int age;
};

// 结构体指针作为函数参数
void showStudentData(struct student *st) {
printf("\nStudent:\n");
printf("Name: %s\n", st->name);
printf("Number: %d\n", st->number);
printf("Age: %d\n", st->age);
}

int main() {
// New Student Record Creation
struct student st1;
struct student st2;

// Filling Student 1 Details
strcpy(st1.name, "Krishna");
st1.number = 5;
st1.age = 21;

// Filling Student 2 Details
strcpy(st2.name, "Max");
st2.number = 9;
st2.age = 15;

// Displaying Student 1 Details
showStudentData(&st1);

// Displaying Student 2 Details
showStudentData(&st2);

return 0;
}
``````

`->` 操作符允许通过指针访问结构体的成员。

`(*st).age``st->age` 相同。 同样，当使用 typedef 命名结构时，仅使用 typedef 名称以及 `*` 和指针名称来声明指针。

【题目】填空，声明一个指向结构的指针并使用该指针访问结构成员 `y`

``````struct Point {
int x;
int y;
} p1;
struct Point ____ptr = &p1;
ptr->x = 3;
ptr____y = 4;
``````

### 2.3 结构体作为函数参数

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

typedef struct {
int id;
char title[40];
float hours;
} course;

void update_course(course *class);
void display_course(course class);

int main() {
course cs2;
update_course(&cs2);
display_course(cs2);
return 0;
}

void update_course(course *class) {
strcpy(class->title, "C++ Fundamentals");
class->id = 111;
class->hours = 12.30;
}

void display_course(course class) {
printf("%d\t%s\t%3.2f\n", class.id, class.title, class.hours);
}
``````

【题目】对于要更改 struct 变量中的实际值的函数：

A. 不需要参数

B. 指针参数是必需的

C. 数组参数是必需的

B

### 2.4 结构体数组

``````#include <stdio.h>

typedef struct {
int h;
int w;
int l;
} box;

int main() {
box boxes[3] = {{2, 6, 8},
{4, 6, 6},
{2, 6, 9}};
int k, volume;

for (k = 0; k < 3; k++) {
volume = boxes[k].h * boxes[k].w * boxes[k].l;
printf("box %d volume %d\n", k, volume);
}
return 0;
}
``````

【题目】填空，声明一个 point 结构体和一个 point 结构体数组：

``````___struct {
int x;
int y;
} point;
___points[3] = {{1, 2}, {3, 4}, {5, 6}};
``````

typedef

point

## 3. 联合体 Union

### 3.1 联合体 Union

``````#include <stdio.h>

union val {
int int_num;
float fl_num;
char str[20];
};

int main() {
union val test;
test.int_num = 42;
printf("%d", test.int_num);
return 0;
}
``````

``````#include <stdio.h>

union val {
int int_num;
float fl_num;
char str[20];
};

int main() {
union val u1;
union val u2;
u1.int_num = 42;
u2 = u1;
printf("%d", u2.int_num);
return 0;
}
``````

【题目】填空，声明一个联合体：

``````___val {
int int_num;
float fl_num;
char str[20];
___
``````

union

};

### 3.2 访问联合体成员

Code1
``````#include <stdio.h>

union val {
int int_num;
float fl_num;
char str[20];
};

int main() {
union val test;

test.int_num = 123;
test.fl_num = 98.76;
strcpy(test.str, "hello");

printf("%d\n", test.int_num);
printf("%f\n", test.fl_num);
printf("%s\n", test.str);
return 0;
}

``````

【题目】填空，声明联合体 `val` 并访问它的成员变量：

``````___val {
int int_num;
float fl_num;
};
union val test;
___int_num = 123;
test.fl_num = 98.76;
``````

union

test.

### 3.3 结构体中的联合体

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

typedef struct {
char make[20];
int model_year;
int id_type; /* 0 for id_num, 1 for VIN */
union {
int id_num;
char VIN[20];
} id;
} vehicle;

int main() {
vehicle car1;
strcpy(car1.make, "Ford");
car1.model_year = 2017;
car1.id_type = 0;
car1.id.id_num = 123098;

printf("Car %s, %d", car1.make, car1.model_year);

return 0;
}
``````

`id_type` 跟踪了当前联合体存储那个具体哪个成员的值。以下语句显示 `car1` 数据，并使用 `id_type` 确定要读取的联合成员：

Code1
``````/* display vehicle data */
printf("Make: %s\n", car1.make);
printf("Model Year: %d\n", car1.model_year);
if (car1.id_type == 0)
printf("ID: %d\n", car1.id.id_num);
else
printf("ID: %s\n", car1.id.VIN);
``````

``````___ person {
int age;
char name[40];
___ {
int id_num;
char text[20];
} passport;
};
``````
``````struct
union
``````

## 4. 联合体的妙用

### 4.1 联合体指针

Code1
``````union val {
int int_num;
float fl_num;
char str[20];
};

union val info;
union val *ptr = NULL;
ptr = &info;
ptr->int_num = 10;
printf("info.int_num is %d", info.int_num);
``````

`(*ptr).int_num``ptr->int_num` 作用相同。

``````___ val {
int int_num;
float fl_num;
};

union val info;
union val ___ ptr = ___ info;
``````

union

`*`

`&`

### 4.2 联合体作为函数参数

Code1
``````union id {
int id_num;
char name[20];
};

void set_id(union id *item) {
item->id_num = 42;
}

void show_id(union id item) {
printf("ID is %d", item.id_num);
}
``````

``````union passport {
int id_num;
char text[20];
};

void show(___ passport p) {
printf("ID is %d", ___.id_num);
}
``````

union

p

### 4.3 联合体数组

Code1
``````union val {
int int_num;
float fl_num;
char str[20];
};

union val nums[10];
int k;

for (k = 0; k < 10; k++) {
nums[k].int_num = k;
}

for (k = 0; k < 10; k++) {
printf("%d  ", nums[k].int_num);
}
``````

Code1
``````union type {
int i_val;
float f_val;
char ch_val;
};
union type arr[3];
arr[0].i_val = 42;
arr[1].f_val = 3.14;
arr[2].ch_val = 'x';
``````

``````union test {
int int_num;
float fl_num;
};
___ test nums[2];
nums[0] ___int_num = 42;
``````

union

`.`

## 5. 小测验

### 5.1 练习-1

``````___time {
int minutes;
int hours;
___;
``````

struct

}

### 5.2 练习-2

``````___struct {
int width;
int height;
} shape;

___sh;
sh.width = 3;
sh.height = 4;
``````

typedef

shape

### 5.3 练习-3

``````struct ship {
int x;
int y;
} sh1;
___ ship *ptr = ___ sh1;
ptr->x = 3;
ptr ___ y = 4;
``````

`struct`

`&`

`->`

``````struct ship {
int x;
int y;
} sh1;

struct ship *ptr = &sh1; // 将 ptr 指向 sh1 的地址
ptr->x = 3; // 通过 ptr 指针访问 sh1 的 x 成员并赋值为 3
ptr->y = 4; // 通过 ptr 指针访问 sh1 的 y 成员并赋值为 4
``````

### 5.4 练习-4

``````___values {
int i_val;
float f_val;
char c_val;
};
union ___ val;
___.c_val = 'a';
``````

union

values

val

### 5.5 练习-5

``````___values {
int i_val;
float f_val;
char c_val;
};
union ___ nums[3];
nums[0].i_val = 42;
___[1].f_val = 3.14;
nums[2].c_val = 'f';
``````

union

values

nums

AI悦创·编程一对一

AI悦创·推出辅导班啦，包括「Python 语言辅导班、C++ 辅导班、java 辅导班、算法/数据结构辅导班、少儿编程、pygame 游戏开发、Linux、Web、Sql」，全部都是一对一教学：一对一辅导 + 一对一答疑 + 布置作业 + 项目实践等。当然，还有线下线上摄影课程、Photoshop、Premiere 一对一教学、QQ、微信在线，随时响应！微信：Jiabcdefh

C++ 信息奥赛题解，长期更新！长期招收一对一中小学信息奥赛集训，莆田、厦门地区有机会线下上门，其他地区线上。微信：Jiabcdefh

• 0
• 0
• 0
• 0
• 0
• 0

• 按正序
• 按倒序
• 按热度