复合类型
概述
有时我们需要将不同类型的数据组合成一个有机的整体,如:一个学生有学号/姓名/性别/年龄/地址等属性, 这时候可通过结构体实现
1. 结构体 struct
结构体(struct)可以理解为用户自定义的特殊的复合的“数据类型
变量的定义和初始化
- 定义结构体变量的方式:
- 先声明结构体类型再定义变量名
- 在声明类型的同时定义变量
结构体大小
结构体大小,由内部数据决定的
如果是空的结构, 是由内部数据类型决定的
#include <stdio.h>
#include <string.h>// 结构体 struct
// 不同类型组合成一个有机的整体,组装成新的数组类型// 初始化
struct stu
{int id;char name[20];int age;float score;
} student;// 赋值
// 单个赋值
struct stu student = {1, "张三", 18, 100.0};// 多个赋值[]
// struct stu student[] = {
// {1, "张三", 18, 100.0},
// {2, "王二麻", 20, 99.0}};// struct tea
// {
// char name[20];
// int age;
// } teacher = {"李四", 20};int main()
{printf("id = %d", student.id);printf("name = %s", student.name);printf("age = %d", student.age);printf("score = %f", student.score);// 修改整型student.id = 2;printf("id = %d", student.id);// 修改字符strcpy(student.name, "李四");printf("name = %s", student.name);// 结构体大小,由内部数据决定的// 如果是空的结构, 是由内部数据类型决定的printf("sizeof(student) = %d", sizeof(student));return 0;
}
结构体作为参数
传值是指将参数的值拷贝一份传递给函数,函数内部对该参数的修改不会影响到原来的变量
传址是指将参数的地址传递给函数,函数内部可以通过该地址来访问原变量,并对其进行修改。
#include <stdio.h>
#include <string.h>struct stu
{char name[20];int age;
};void show_stucct(struct stu student)
{printf("姓名:%s\n", student.name);printf("年龄:%d\n", student.age);strcpy(student.name, "王二麻子");printf("修改后年龄:%s\n", student.name);
};// 函数参数传递结构体指针
// 指针类型需要使用->操作符void show_stucct_pointer(struct stu *student)
{strcpy(student->name, "王二麻子666");printf("姓名:%s\n", student->name);printf("年龄:%d\n", student->age);
};int main()
{struct stu s = {"张三", 18};show_stucct(s);show_stucct_pointer(&s);printf("-----------------------\n");// 指针函数传递时,会在外面修改printf("姓名:%s\n", s.name);printf("年龄:%d\n", s.age);return 0;
}
2. 共用体 union
共用体union是一个能够在同一个存储空间存储不同类型的数据的类型
-------------------------------以下内容,明天更新,敬请期待----------------------------------