C语言结构体对齐,超详细,超易懂

结构体对齐规则
结构体的第一个成员总是存放在结构体变量开辟的空间的起始地址
其它成员变量要存储在一个名叫对齐数的整数倍的地址
结构体总大小为最大对齐数的整数倍,结构体内每一个变量都会产生一个对齐数,取其最大的对齐数
如果是嵌套结构体,那么嵌套的结构体存储在嵌套结构体的成员的最大对齐数的整数倍地址处,包含嵌套结构体的结构体大小为自己成员的对齐数和嵌套结构体的成员的对齐数的最大对齐数的整数倍
结构体Tmp与结构体Cmd,结构体Msg的变量在内存的存放位置
结构体Tmp,大小为12

 

结构体Cmd,大小为8

 

结构体Msg,大小为8

 

示例

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


struct Tmp
{
char c1;
int a;
char c2;
};

struct Cmd
{
char c1;
char c2;
int a;
};

struct Msg
{
int a;
char c1;
char c2;
};

int main(int argc,char *argv[])
{
struct Tmp t;
struct Cmd c;
struct Msg m;

memset(&t,0,sizeof(struct Tmp));
memset(&c,0,sizeof(struct Cmd));
memset(&m,0,sizeof(struct Msg));

printf("int size is %ld\n",sizeof(int)); //4
printf("char size is %ld\n",sizeof(char)); //1
printf("int* size is %ld\n",sizeof(int *)); //8
printf("char* size is %ld\n",sizeof(char *)); //8

printf("Tmp struct size is %ld\n",sizeof(struct Tmp)); //12
printf("Tmp struct variable size is %ld\n",sizeof(t)); //12
printf("Cmd struct size is %ld\n",sizeof(struct Cmd)); //8
printf("Cmd struct variable size is %ld\n",sizeof(c)); //8
printf("Msg struct size is %ld\n",sizeof(struct Msg)); //8
printf("Msg struct variable size is %ld\n",sizeof(m)); //8

return 0;
}

嵌套结构体对齐
嵌套结构体Msg1,大小为20


嵌套结构体Msg2,大小为16

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct Tmp // size = 12
{
char c1;
int a;
char c2;
};

struct Cmd // size = 8
{
char c1;
char c2;
int a;
};

struct Msg1
{
int a;
char c1;
char c2;
struct Tmp t;
};

struct Msg2
{
int a;
char c1;
char c2;
struct Cmd c;
};

int main(int argc, char *argv[])
{
struct Tmp t;
struct Cmd c;
struct Msg1 m1;
struct Msg2 m2;

memset(&t, 0, sizeof(struct Tmp));
memset(&c, 0, sizeof(struct Cmd));
memset(&m1, 0, sizeof(struct Msg1));
memset(&m2, 0, sizeof(struct Msg2));

printf("Msg1 struct size is %ld\n", sizeof(struct Msg1)); // 20
printf("Msg1 struct variable size is %ld\n", sizeof(m1)); // 20

printf("Msg2 struct size is %ld\n", sizeof(struct Msg2)); // 16
printf("Msg2 struct variable size is %ld\n", sizeof(m2)); // 16

return 0;
}
https://blog.csdn.net/weixin_54076783/article/details/126694593

https://blog.csdn.net/qq_67838572/article/details/126918769

https://blog.csdn.net/earther19949/article/details/96430991

typedef和define 的区别:

1、typedef仅限于为类型定义符号名称,#define不仅可以为类型定义别名,也能为数值定义别名,比如将2定义为true

2、typedef是由编译器执行解释的,#define语句是由预编译器进行处理的。

http://yifeichongtian.spaces.eepw.com.cn/articles/article/item/113376

https://blog.csdn.net/earther19949/category_10338923.html?spm=1001.2014.3001.5482

posted @ 2023-02-04 12:34  师大无雨  阅读(393)  评论(0)    收藏  举报