#include <stdio.h>
#include <string.h>
struct student
{
int num;
char name[20];
char sex;
float score;
};
main()
{
struct student stu_1, *p;
printf("steudent len is %d\n", sizeof(struct student));
}
*****
理论计算:结构体长度为29,但是编译器计算为32,原因在哪里?
解决的办法,分别计算包含数据的时候结构体的长度:
当
struct student
{
int num;
};------长度为4;
struct student
{
int num;
char name[20];
};-----长度为24;
struct student
{
int num;
char name[20];
char sex;
}; -----长度为28, 原因在这里,为了内存边缘对齐,分配了4个字节;
struct student
{
int num;
char name[20];
char sex;
float score;
}; ------长度为32
******************
如果:
struct student
{
int num;
char name[20];
char sex;
char sex1;
float score;
}; --长度还是32,
但是
struct student
{
int num;
char name[20];
char sex;
float score;
char sex1;
}; ----长度为36
印象加深
5 struct stu
6 {
7 double i;
8 char a[20];
9 char b;
10 char d;
11 char e;
12 char f;
13
14 float c;
15 } //这个结构体中char b d e f 无论有没有,他的字节数都是36个。
3 int main()
4 {
5 struct stu
6 {
7 double i;
8 char a[20];
9 char b;
10 char d;
11 char e;
12 char f;
13 char g;
14 float c;
15 }; //这里面多加了一个char g 字符型数组字节数溢出(原先是8*3=24个) 所以多加了4个字节 ,也就是40个。
最后:无论struct还是union中,有int参与,都是按照4个字节对齐存放,
计算:占12个字节,但是去掉 char position[10]----10,
int banji----4个字节
为什么是12个?要么是4, 要么是10?
测试:
union
{
int banji;
char position[11];
}category;--- 占12个字节
union
{
// int banji;
char position[11];
}category;占11个字节;
两者比较,就是有了int类型后,编译器按照4字节对齐方式来分配内存了。