為什麼在 C/C++ 中,結構體的 sizeof() 結果不等於每個成員 sizeof() 之和?


使用 sizeof() 獲取的結構體型別元素的大小並不總是等於每個成員的大小之和。有時編譯器會新增一些填充來避免對齊問題。因此大小可能會發生變化。當一個結構體成員後面跟著一個更大尺寸的成員或在結構體的末尾時,就會新增填充。不同的編譯器有不同的對齊約束。在 C 標準中,結構體的總對齊取決於實現。

案例 1

在這種情況下,double 型別的 z 長度為 8 位元組,大於 x(4 位元組)。因此會新增另外 4 位元組的填充。此外,short 型別資料 y 在記憶體中佔用 2 位元組的空間,因此會新增額外的 6 位元組作為填充。

示例程式碼

#include <stdio.h>
struct myStruct {
   int x; //Integer takes 4 bytes, and padding 4 bytes
   double z; //Size of double is 8-byte, no padding
   short int y; //Size of short is 2-byte, padding 6-bytes
};
main() {
   printf("Size of struct: %d", sizeof(struct myStruct));
}

輸出 2

Size of struct: 24

案例 2

在這種情況下,double 型別首先插入,它佔用 8 位元組的空間。現在新增整數 x(4 位元組)。所以還有另外 4 位元組的空間。當新增 short 型別的 y 時,它可以放置在額外的 4 位元組空間中,並佔用總共 16 位元組的空間。

示例程式碼

#include <stdio.h>
struct myStruct {
   double z; //Size of double is 8-byte, no padding
   int x; //Integer takes 4 bytes, and padding 4 bytes
   short int y; //Size of short is 2-byte, padding 6-bytes
};
main() {
   printf("Size of struct: %d", sizeof(struct myStruct));
}

輸出 2

Size of struct: 16

案例 3

在第三種情況下,它也佔用 16 位元組的記憶體空間,但排列方式不同。由於第一個成員是 double,因此它首先放置,然後新增 short 型別資料。現在當嘗試插入整數時,它可以放置在剩餘的 6 位元組區域中。因此,short 後面有一個填充,但整數資料後面不需要填充。

示例程式碼

#include <stdio.h>
struct myStruct {
   double z; //Size of double is 8-byte, no padding
   short int y; //Size of short is 2-byte, padding 6-bytes
   int x; //Integer takes 4 bytes, and padding 4 bytes
};
main() {
   printf("Size of struct: %d", sizeof(struct myStruct));
}

輸出 2

Size of struct: 16

更新於: 2019年7月30日

764 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.