【CC++】sizeof问题总结

xiaoxiao2021-02-28  17

以下默认使用32位编译器!


空结构体

struct A{ }; cout << sizeof(A) << endl; //1

记住,此时输出就是1


只含有一个类型的结构体

char

struct A{ char a; }; cout << sizeof(A) << endl; //1

short

struct A{ short a; }; cout << sizeof(A) << endl; //2

int /long/float

struct A{ int a; //long == long int //float }; cout << sizeof(A) << endl; //4

double/long long

struct A{ double a;//long long }; cout << sizeof(A) << endl; //8

含有多个相同类型的结构体

char

struct A{ char a, b; }; cout << sizeof(A) << endl; //2

不在举例说明,只是简单的叠加关系。

含有多个不相同类型的结构体——对齐问题

char + int

struct A{ char a; int b; }; cout << sizeof(A) << endl; //8

|–char–|———–|———–|———–| |——————–int——————–|

char + short + int

struct A{ char a; short b; int c; }; cout << sizeof(A) << endl; //8

|–char–|——–short——–|———–| |——————–int——————–|

char + int + short

struct A{ char a; int b; short c; }; cout << sizeof(A) << endl; //12

|–char–|———–|———–|———–| |——————–int——————–| |——-short——|———–|———–|

注意:对于上面的两种情况,编译器给出不同的解释。所以,在编写代码的时候,推荐从小到大的类型编写结构体,这样可以优化一些内存空间。

(完)


参考

http://blog.csdn.net/hsd2012/article/details/50968793

转载请注明原文地址: https://www.6miu.com/read-250085.html

最新回复(0)