gpt4 book ai didi

c - 为什么 sizeof() 在 64 位 cpu 上不同?

转载 作者:太空狗 更新时间:2023-10-29 17:26:43 26 4
gpt4 key购买 nike

考虑以下示例:

#include <stdio.h>
#include <inttypes.h>

struct A {
uint32_t i1;
uint32_t i2;
uint32_t i3;
uint64_t i4;
uint32_t i5;
uint32_t i6;
uint32_t i7;
uint64_t i8;
uint32_t i9;
};

struct B {
uint32_t i1;
uint32_t i2;
uint32_t i3;
uint32_t i4;
uint32_t i5;
uint32_t i6;
uint32_t i7;
uint64_t i8;
uint64_t i9;
};

int
main()
{
struct A a;
struct B b;

printf("sizeof(a) = %u, sizeof(b) = %u\n", sizeof(a), sizeof(b));

return 0;
}

输出是:

$ ./t2 
sizeof(a) = 56, sizeof(b) = 48
$

为什么它们在 64 位机器上不同?在 32 位平台上结果是相同的:

$ ./t2
sizeof(a) = 44, sizeof(b) = 44

最佳答案

一些图表可以帮助您理解:

32 位:

+----+----+----+----+----+----+----+----+----+----+----+
| i1 | i2 | i3 | i4 | i5 | i6 | i7 | i8 | i9 | Struct A
+----+----+----+----+----+----+----+----+----+----+----+

+----+----+----+----+----+----+----+----+----+----+----+
| i1 | i2 | i3 | i4 | i5 | i6 | i7 | i8 | i9 | Struct B
+----+----+----+----+----+----+----+----+----+----+----+

64 位:

+---------+---------+---------+---------+---------+---------+---------+
| i1 | i2 | i3 |~~~~| i4 | i5 | i6 | i7 |~~~~| i8 | i9 |~~~~| Struct A
+---------+---------+---------+---------+---------+---------+---------+

+---------+---------+---------+---------+---------+---------+
| i1 | i2 | i3 | i4 | i5 | i6 | i7 |~~~~| i8 | i9 | Struct B
+---------+---------+---------+---------+---------+---------+
  • + :地址边界
  • ~ : 填充

关于c - 为什么 sizeof() 在 64 位 cpu 上不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/951746/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com