关于struct的空间问题

学术版

ppip @ 2023-02-21 19:24:20

#include <bits/stdc++.h>
using namespace std;
struct i2___ {int x,y;}; // 名字太短制表符会崩
struct i1_ll1 {int x;long long y;};
struct i3_ll1 {int x,y,z;long long w;};
struct s3_i1 {short x,y,z;int w;};
struct s1_i1_ll1 {short x;int y; long long z;};
template <typename T>
void test(int expected) {
    cout<<"Testsing: "<<typeid(T).name()+1<<",\texpected=\t"<<expected<<",\tsize=\t"<<sizeof(T)<<endl;
}
int main() {
    test<i2___>(8);
    test<i1_ll1>(12);
    test<i3_ll1>(20);
    test<s3_i1>(10);
    test<s1_i1_ll1>(14);
    return 0;
}
Testsing: i2___,        expected=       8,      size=   8
Testsing: i1_ll1,       expected=       12,     size=   16
Testsing: i3_ll1,       expected=       20,     size=   24
Testsing: s3_i1,        expected=       10,     size=   12
Testsing: s1_i1_ll1,    expected=       14,     size=   16

结论:结构体有莫名其妙的空间常数。无法解释。


by Killer_joke @ 2023-02-21 19:31:14

有个东西叫做对齐对齐


by dehsirehC @ 2023-02-21 19:33:01

可以 #pragma pack(1) 取消对齐


by ppip @ 2023-02-21 19:44:15

thx


|