使用 sizeof 的 c++ 中的不同结果

Different results in c++ using sizeof

本文关键字:结果 c++ sizeof 使用      更新时间:2023-10-16

我在测试期间sizeof()面临一个奇怪的结果。T1T2的大小与T2中使用的类型如何小于T1

#include <iostream>
using namespace std;
struct T1 {
    int     id;
    int     enable;
};
struct T2 {
    int     id;
    char    enable;
};

int main() {
    cout << sizeof(T1) << endl; // Print 8
    cout << sizeof(T2) << endl; // Print 8
    return 0;
}

填充T2以进行对齐。

也就是说,它包含未使用的字节,以便T2数组将所有T2.id dword 对齐。