#include <stdio.h>
//结构体声明
struct student{
int num;
char name[20];
char sex;
int age;
float score;
char address[100];
};
int main() {
struct student std1={1000,"vvq",'1',10,99.2,"XiShan"};//定义及初始化
struct student sarr[4];//结构体数组
int i;
std1.num=1005;//可以在打印之前更改
printf("%d %s %c %d %5.2f %s\n",std1.num,std1.name,std1.sex,std1.age,std1.score,std1.address);//结构体输出必须单独访问每个成员
// scanf("%d%s %c%d%f%s",&std1.num,std1.name,&std1.sex,&std1.age,&std1.score,std1.address);//数组名自带地址不需要取地址
//%c 不会忽略前方缓冲区里的\n需要空格 其他的都会忽略
printf("--------------------------------------------------------------\n");
//一个数组下标相当于一个结构体 包含每一个成员
for (i=0; i<4;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].address);
}
for(i=0;i<4;i++)
{
printf("%d %s %c %d %5.2f %s\n",sarr[i].num,sarr[i].name,sarr[i].sex,sarr[i].age,sarr[i].score,sarr[i].address);
}
return 0;
}
结构体对齐 --- 高效的取内存上的数据
结构体大小必须是其最大成员的整数倍 大小不算数组
最大是int 4个字节
4+20(是4的整数倍)+4(1变成4)+4+4+32(30不是4的整数倍所以加2)=68
练习一下
#include <stdio.h>
struct student_type1{
double score;
short age;
};
struct student_type2{
double score;
short age;
int height;
};//8+8=16
struct student_type3{
int height;
short age;
char sex;
};
int main() {
struct student_type1 s1;
struct student_type2 s2;
struct student_type3 s3;
printf("student_type1 size=%d\n",sizeof (s1));
printf("student_type2 size=%d\n",sizeof (s2));
printf("student_type3 size=%d\n",sizeof (s3));
return 0;
}
题解
#include <stdio.h>
struct student_type1{
double score; //8byte
short age;//短整型 2 但变成8
};//8+8=16
struct student_type2{
double score;
//两个小的和不满8 可以填充在一起 并不是三个8字节
short age;
int height;
};//8+8=16
struct student_type3{
int height; //4字节
//2和1不满4 填充在一起为4
short age;
char sex;
};
int main() {
struct student_type1 s1;
struct student_type2 s2;
struct student_type3 s3;
printf("student_type1 size=%d\n",sizeof (s1));
printf("student_type2 size=%d\n",sizeof (s2));
printf("student_type3 size=%d\n",sizeof (s3));
return 0;
}