一.结构体的定义
结构体在 C 语言中是一种用户自定义的数据类型,由一系列具有相同类型或不同类型的数据构成的数据集合,也叫结构。它和其他类型基础数据类型一样,只不过结构体可以做成想要的数据类型,以方便日后的使用。在实际项目中,结构体是大量存在的。研发人员常使用结构体来封装一些属性来组成新的类型。由于 C 语言无法操作数据库,所以在项目中通过对结构体内部变量的操作将大量的数据存储在内存中,以完成对数据的存储和操作。
结构体可以被声明为变量、指针或数组等,用以实现较复杂的数据结构。在定义结构体时需要注意数据成员的对齐规则和结构体的整体对齐规则。
二.定义方式
在main函数中初始化结构体:struct+结构体名+变量名,类似于 struct+int+a;{}大括号内存放元素,从左至右元素类型需要与定义的顺序一致
例子:
#include <stdio.h>
struct Person {
char name[20];
int age;
char sex[20];//char类型需要加上空间数量
};//结构体的声明,这里的Person类似于C语言内置的,int,char,double
struct Animal {
int sum;
char spe[20];
char con[20];
};
int main() {
struct Person person1 = { "Alice", 20, "female"}; // 初始化结构体:struct+结构体名+变量名,类似于 struct+int+a;从左至右元素类型需要与定义的顺序一致
printf("Name: %s\nAge: %d\nSex: %s\n",person1.name,person1.age,person1.sex);//打印结构体中的元素
printf("\n");
struct Animal u = { 20,"tigger","China" };
printf("sun:%d\nspe:%s\ncon:%s\n", u.sum, u.spe, u.con);
return 0;
三.结构体也可以存放多个数据
例子:
#include <stdio.h>
#include <string.h>
// 定义 student 结构体
struct student {
char name[20]; // 姓名
int id; // 学号
int score[3]; // 语数外三门成绩
};
int main() {
// 初始化三个学生信息
struct student stu1 = { "李明", 10001, {99, 80, 80} };
struct student stu2 = { "张三", 10002, {100, 50, 80} };
struct student stu3 = { "王旭", 10025, {100, 99, 89} };
// 打印学生信息
printf("学生信息如下:\n");
printf("姓名\t学号\t语文\t数学\t外语\n");
printf("-------------------------\n");
printf("%s\t%d\t%d\t%d\t%d\n", stu1.name, stu1.id, stu1.score[0], stu1.score[1], stu1.score[2]);
printf("%s\t%d\t%d\t%d\t%d\n", stu2.name, stu2.id, stu2.score[0], stu2.score[1], stu2.score[2]);
printf("%s\t%d\t%d\t%d\t%d\n", stu3.name, stu3.id, stu3.score[0], stu3.score[1], stu3.score[2]);
return 0;
}
运行结果: