struct A -->8 bytes
{
char c;
char d;
//2 padding here
int i;
};
struct B -->12 bytes
{
char c;
//3 padding here
int i;
char d;
//3 padding here
};
现在,我不理解以下示例:
typedef struct { -->**shouldn't it be 12 bytes**
int a;
char *str;
} TestS;
TestS s;
int main(int argc, char *argv[]) {
printf("An int is %lu bytes\n", sizeof( int )); -->4
printf("A Char * is %lu bytes\n", sizeof( char *)); -->8
printf("A double is %lu bytes\n", sizeof( double )); -->8
printf("A struct is %lu bytes\n", sizeof s); -->why 16?
return 0;
}
起初我认为可能是对齐到8*N字节(因为我使用的是ubuntu-64),所以我尝试了更多的结构体。
typedef struct {
int i;
char *str;
} stru_12;
typedef struct {
int i;
char *str;
char c;
} stru_13;
typedef struct {
int i;
char str[7];
} stru_11;
typedef struct {
char *str;
double d;
} stru_16;
stru_12 test12;
stru_13 test13;
stru_11 test11;
stru_16 test16;
int main (int argc, char *argv[]) {
printf("A test12 is %lu bytes, address is %p\n", sizeof test12, &test12);
printf("A test13 is %lu bytes, address is %p\n", sizeof test13, &test13);
printf("A test11 is %lu bytes, address is %p\n", sizeof test11, &test11);
printf("A test16 is %lu bytes, address is %p\n", sizeof test16, &test16);
}
结果:
test12是16字节,地址为0x601060
test13是24字节,地址为0x601090
test11是12字节,地址为0x601080
test16是16字节,地址为0x601070
很抱歉这么长。
我的问题是:
为什么test12(int + char *)是16字节,而test13(int + char * + char)是24字节?(似乎偏爱 8 * N ,但允许12字节)
为什么结构的地址差异是16个寻址单元(更多填充?)?
供您参考:
缓存对齐:64
地址大小:36位物理,48位虚拟
Ubuntu 14.04.1 LTS x86_64
sizeof(struct stru_12)
等方式?这样可以减少视觉干扰。 - Kerrek SB