gpt4 book ai didi

c - GCC 为什么会生成错误的结构偏移量?

转载 作者:行者123 更新时间:2023-12-02 07:23:57 25 4
gpt4 key购买 nike

我有这个代码:

mbr.h:

struct mbr_partition {
char flags;
char start_head;
char start_sector;
char start_cyl;
char type;
char last_head;
char last_sector;
char last_cyl;
uint32_t start;
uint32_t size;
};

struct mbr {
char bootloader[446];
struct mbr_partition partition1;
struct mbr_partition partition2;
struct mbr_partition partition3;
struct mbr_partition partition4;
char magic[2];
};

和:main.c:

int main()
{
printf("%d\n", sizeof(struct mbr));
printf("%d\n", sizeof(struct mbr_partition));
printf("%d\n", sizeof(long));
struct mbr mbr;
printf("%d, %d\n", ((char *) &mbr.magic) - ((char *) &mbr), sizeof(mbr)$
printf("1: %d\n", ((char *) &mbr.partition1) - ((char *) &mbr));
printf("2: %d\n", ((char *) &mbr.partition2) - ((char *) &mbr));
printf("3: %d\n", ((char *) &mbr.partition3) - ((char *) &mbr));
printf("4: %d\n", ((char *) &mbr.partition4) - ((char *) &mbr));
return 0;
}

并输出:

516
16
8
512, 516
1: 448
2: 464
3: 480
4: 496

为什么size是516字节(应该是512)?为什么 partition1 偏移量是 448 而不是 446?我该如何解决?

最佳答案

因为可能会有一些填充字节或填充位。

引自 N1570 6.7.2.1 结构和 union 说明符:(强调我的)

15 Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.

关于c - GCC 为什么会生成错误的结构偏移量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36376426/

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