为什么sizeof出来大小不对
- C/C++ code
#include <stdio.h>#include <stdlib.h>#include <string.h>int main(){ struct jb{ char actor[25]; struct jb *next; }; struct jb *bond; int n; /* Create the first structure in the list */ bond = (struct jb *)malloc(sizeof(struct jb)); printf("struct jb sizeof is %d\n", n = sizeof(struct jb)); printf("struct bond->actor sizeof is %d\n", n = sizeof(bond->actor)); printf("struct bond->next sizeof is %d\n", n = sizeof(bond->next)); /* Fill the structure */ strcpy(bond->actor, "Sean Connery"); bond->next = NULL; /* End of list */ /* Display the results */ printf("The first structure has been created:\n"); printf("\tbond->actor = %s\n", bond->actor); printf("\tnext structure address = %p\n", bond->next); return(0);}输出是struct jb 是32, 但数组是25, 指针是4,多出来的3是什么
[解决办法]
C/C++对齐的规则,你可以参考这篇(http://rex.zhang.name/index.php/2011/11/652/)文章。
[解决办法]
内存对齐的问题
内存对齐的原则有两个
1.结构体内的成员变量的偏移量是变量大小的整数倍。
2.结构体的大小事所有成员变量中最大成员大小的整数倍!
就按上述规则可以计算结构体的大小。
struct jb{
char actor[25]; 偏移量为0,是25的整倍数
struct jb *next; 大小为4,偏移量25不是4的整数倍,空出三个字节,使偏移量为28,也 就是4的整数倍,这时候把指针的四个字节存在里面
};
于是结构就是28+4=32