gpt4 book ai didi

c - 了解我的结构的大小

转载 作者:行者123 更新时间:2023-12-02 02:11:02 24 4
gpt4 key购买 nike

我的代码:

typedef struct {
int sizeOfMyIntArray;
int* myIntArray;
float someFloat;
} my_struct_foo;

int main() {
printf("The size of float is: %d\n", sizeof(float));
printf("The size of int is: %d\n", sizeof(int));
printf("The size of int* is: %d\n", sizeof(int*));
printf("The size of my_struct_foo is: %d\n", sizeof(my_struct_foo));
return 0;
}

我想这很简单。虽然,我对这个程序的结果输出有点惊讶......

The size of float is: 4
The size of int is: 4
The size of int* is: 8
The size of my_struct_foo is: 24

我有一个 float 、一个整数和一个指向整数的指针。我在想:4 + 4 + 8 = 16...不是 24。为什么我的结构大小是 24 而不是 16?

最佳答案

对齐和填充。 int* 应在八字节边界上对齐,因此编译器在 int 和指针之间以及 之后(或之前)插入四个字节的填充code>float 使结构的大小成为指针大小的倍数,并使指针正确对齐。

如果您重新排序成员,

typedef struct {
int sizeOfMyIntArray;
float someFloat;
int* myIntArray;
} my_struct_foo;

指针将在没有任何填充的情况下正确对齐,因此结构的大小(很可能允许编译器添加填充,即使不需要,但我知道没有人这样做)为 16。

关于c - 了解我的结构的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12877920/

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