Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

ทำไม sizeof struct ไม่เท่ากับผลรวม sizeof ของแต่ละ member ใน C/C++


ขนาดของ struct type element ที่ sizeof() คืน ไม่เสมอไปเท่ากับขนาดของแต่ละ member บางครั้ง compiler เพิ่ม padding เพื่อหลีกเลี่ยง alignment issues ทำให้ขนาดเปลี่ยน Padding เพิ่มเมื่อ structure member ตามด้วย member ที่มีขนาดใหญ่กว่า หรือที่ท้ายของ structure Compiler แต่ละตัวมี alignment constraints ต่างกัน ใน C standard total alignment structure ขึ้นกับ implementation

Case 1

double z ยาว 8-byte ใหญ่กว่า x (4-byte) เพิ่ม padding 4-byte อีก short y มี 2-byte เพิ่ม padding 6-bytes

ทำไม sizeof struct ไม่เท่ากับผลรวม sizeof ของแต่ละ member ใน C/C++

ตัวอย่างโค้ด

#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)); }

Output 2

Size of struct: 24

Case 2

double อยู่หน้า ใช้ 8-byte int x (4-byte) เพิ่ม 4-byte space short y วางใน extra 4-byte space ใช้รวม 16-bytes

ทำไม sizeof struct ไม่เท่ากับผลรวม sizeof ของแต่ละ member ใน C/C++

ตัวอย่างโค้ด

#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)); }

Output 2

Size of struct: 16

Case 3

ใช้ 16-byte เช่นกัน แต่ arrangement ต่างกัน double ก่อน แล้ว short ต่อมา int วางใน remaining 6-byte area มี padding หลัง short แต่ไม่ต้องหลัง int

ทำไม sizeof struct ไม่เท่ากับผลรวม sizeof ของแต่ละ member ใน C/C++

ตัวอย่างโค้ด

#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)); }

Output 2

Size of struct: 16