您的位置:首页 > 其它

关于内存对其问题(三)

2011-11-12 20:56 204 查看
http://patmusing.blog.163.com/blog/static/135834960201001432528600/

第一种情况:

struct BBB

{

long num; // 4bytes

char *name; // 4 bytes

short int data; // 2 bytes

char ha; // 1 byte

short ba[5]; // 10 bytes

};

sizeof(BBB) = 24bytes

理由:

1. 很容易知道BBB的内存对齐数是4bytes

2. num和name各为4bytes,已经对齐

3. data和ha加起来是3bytes,因此要补1byte

4. ba共10bytes,因此要补2bytes

第二种情况:

struct BBB

{

long num; // 4 bytes

char *name; // 4 bytes

short int data; // 2 bytes

char ha; // 1 byte

char hb; // 1 byte

short ba[5]; // 10 bytes

};

sizeof(BBB) = 24bytes

理由:

1. 很容易知道BBB的内存对齐数是4bytes

2. num和name各为4bytes,已经对齐

3. data、ha和hb加起来是4bytes,已经对齐

3. ba共10bytes,因此要补2bytes

第三种情况:

struct BBB

{

char hb; // 1 byte

long num; // 4 bytes

char *name; // 4 bytes

short int data; // 2 bytes

char ha; // 1 byte

short ba[5]; // 10 bytes

};

sizeof(BBB) = 28bytes

理由:

1. 很容易知道BBB的内存对齐数是4bytes

2. hb为1byte,因此需要补3bytes

3. num和name各为4bytes,已经对齐

4. data、ha加起来是3bytes,因此要补1byte

5. ba共10bytes,因此要补2bytes

通过上述三种情况,我们可以得出推论:

a. 尽管成员变量一样,如果由于排列的顺序不同,则所得到对象的大小也有可能不同

b. 相同数据类型的成员变量,在结构或类定义时,尽量相邻,这样可以减少空间的消耗

下面再举一个例子,来说明上述推论b:

假定结构BBB定义如下:

struct BBB

{

char ha;

int a;

char hb;

int b;

char hc;

int c;

};

那么sizeof(BBB) = 24bytes

如果结构BBB的定义改为:

struct BBB

{

char ha;

char hb;

char hc;

int a;

int b;

int c;

};

那么sizeof(BBB) = 16bytes

可见在两种情况下结构BBB所能承载的数据量是一样的,但所占用的空间却有很大的不同。

顺便简单复习一下数据类型自身对齐值方面的问题。char类型的对齐数为1byte,short类型为2bytes,int、float和double类型,均为4bytes。由于数据类型有自身对齐值,因此,short类型的变量的起始地址必须为2的倍数,int、float和double类型的变量的起始地址必须为4的倍数。char类型的对齐数为1,所以char类型变量的起始地址,可以在任何有效的位置。请参考下面的代码:

#include <iostream>

using namespace std;

struct foo1

{

char c1; // 0

short s; // 2 ~ 3 s为short类型,因此其起始地址必须是2的倍数

char c2; // 4

int i; // 8 ~ 11 i为int类型,因此其起始地址必须是4的倍数

};

struct foo2

{

char c1; // 0

char c2; // 1

short s; // 2 ~ 3

int i; // 4 ~ 7

};

int main()

{

cout << sizeof(foo1) << endl; // 12

cout << sizeof(foo2) << endl; // 8

return 0;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: