对于结构元素的内存分配 [英] memory allocation for structures elements

查看:141
本文介绍了对于结构元素的内存分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有大约内存是如何分配的结构元素的理解困难。

Hi I am having difficulties in understanding about how the memory is allocated to the structure elements.

例如,如果我有下面结构和焦炭的大小是1,int是分别为4个字节。

For example if i have the below structure and the size of char is 1 and int is 4 bytes respectively.

struct temp
{
char a;
int b;
};

我知道该结构的大小将是8.因为会有3字节的炭后填充,下一个元件应该被放置在4的倍数这样的大小将是8

I am aware that the size of the structure would be 8. Because there will be a padding of 3 bytes after the char, and the next element should be placed in multiple of 4 so the size will be 8.

现在考虑下面的结构。

struct temp
{
int a;     // size is 4
double b;  // size is 8
char c;    // size is 4
double d;  // size is 8
int e;     // size is 4
};

这是O / P我得到了上述strucure

This is the o/p i got for the above strucure

size of node is 40
the address of node is 3392515152 ( =: base)
the address of a in node is 3392515152 (base + 0)
the address of b in node is 3392515160 (base + 8)
the address of c in node is 3392515168 (base + 16)
the address of d in node is 3392515176 (base + 24)
the address of e in node is 3392515184 (base + 32)

的总内存总结为36个字节,为什么它显示为40个字节?
如果我们创建这样的结构数组也是一个数组元素的第一个元素可以是3392515188(基地+ 36)的地方,因为它是4的倍数,但它为什么没有发生这样?

The total memory sum up to 36 bytes, why does it show as 40 bytes? If we create an array of such structure also the first element of the next array element can be place in 3392515188 (base + 36) as it is a multiple of 4, but why is it not happening this way?

任何一个PLZ可以解决我的疑惑。

Can any one plz solve my doubt.

在此先感谢,
Saravana

Thanks in advance, Saravana

推荐答案

看来你的系统上,双击必须有8对齐。

It seems that on your system, double has to have the alignment of 8.

struct temp {
    int a;     // size is 4
    // padding 4 bytes
    double b;  // size is 8
    char c;    // size is 1
    // padding 7 bytes
    double d;  // size is 8
    int e;     // size is 4
    // padding 4 bytes
}; 
// Total 4+4+8+1+7+8+4+4 = 40 bytes

编译器增加了额外的4个字节到结构的末尾,以确保数组[1] .B 将被正确对齐。

没有结束填充(假设数组的地址为0):

Without end padding (assuming array is at address 0):

&array[0]   == 0
&array[1]   == 36
&array[1].b == 36 + 8 == 44  
44 % 8 == 4  ->  ERROR, not aligned!

使用结束填充(假设数组的地址为0):

With end padding (assuming array is at address 0):

&array[0]   == 0
&array[1]   == 40
&array[1].b == 40 + 8 == 48
48 % 8 == 0  ->  OK!

需要注意的是尺寸,路线和内边距取决于所使用的目标系统和编译器。

Note that sizes, alignments, and paddings depend on target system and compiler in use.

这篇关于对于结构元素的内存分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆