有时候需要将不同类型的数据组合为一个整体,以便于引用。例如,一名学生有学号、姓名、性别、年龄、地址等属性,如果针对学生的学号、姓名、年龄等都单独定义一个变量,那么在有多名学生时,变量就难以分清。为此,C 语言提供结构体来管理不同类型的数据组合。声明一个结构体类型的一般形式为:
struct 结构体名
{
成员表列
};
例如
struct student
{
int num; char name[20]; char sex;
int age; float score; char addr[30];
};
//结构体的scanf读取和输出
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct student { //结构体初始化赋值要用大括号
//里边的变量名必须要和main函数中的顺序对应
int num;
char name[20];
char sex;
char age;
float score;
char addr[30];
}; //结构体类型声明,注意最后一定要加分号
int main()
{
struct student s = { 1001,"lele",'M',20,85.4,"Shenzhen" }; //变量名s和结构体名字student不能一样
printf("%d %s %c %d %f %s\n", s.num, s.name, s.sex, s.age, s.score, s.addr);
//结构体输出必须单独去访问内部的每一个成员
return 0;
}
运行结果:
1001 lele M 20 85.400002 Shenzhen
一、结构体的scanf读取和输出
//结构体的scanf读取和输出
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct student { //结构体初始化赋值要用大括号
//里边的变量名必须要和main函数中的顺序对应
int num;
char name[20];
char sex;
char age;
float score;
char addr[30];
}; //结构体类型声明,注意最后一定要加分号
int main()
{
struct student s = { 1001,"lele",'M',20,85.4,"Shenzhen" }; //变量名s和结构体名字student不能一样
struct student sarr[3]; //结构体数组,相当于是一个数组中有三个结构体
int i;
for (i = 0; i < 3; i++)
{
scanf("%d %s %c %d %f %s", &sarr[i].num, &sarr[i].name, &sarr[i].sex, &sarr[i].age, &sarr[i].score, &sarr[i].addr);
}
for (i = 0; i < 3; i++) //结构体数组的输出
{
printf("%d %s %c %d %f %s\n", sarr[i].num, sarr[i].name, sarr[i].sex, sarr[i].age, sarr[i].score, sarr[i].addr);
}
return 0;
}
二、结构体对齐
结构体的大小必须是其最大成员的整数倍。
最大成员不包含数组。
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct student { //结构体初始化赋值要用大括号
//里边的变量名必须要和main函数中的顺序对应
int num;
char name[20];
char sex;
char age;
float score;
char addr[30];
};
以上成员个数是4,最大成员是4字节。
结构体为什么要对齐:为了cpu能够高效的取走内存中的数据。
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct student_tupe1 {
//整体按照最大的整数倍8个对齐,所以打印16
double score; //8字节
short age; //2字节
};
struct student_tupe2 {
double score; //8字节
int height; //4字节
short age; //2字节
};
struct student_tupe3 {
int height; //4字节
char sex; //1字节
short age; //2字节
};
int main()
{
struct student_tupe1 s1;
struct student_tupe2 s2;
struct student_tupe3 s3;
printf("s1 size=%d\n", sizeof(s1));
printf("s2 size=%d\n", sizeof(s2));
printf("s3 size=%d\n", sizeof(s3));
return 0;
}
运行结果:
s1 size=16
s2 size=16
s3 size=8