联合与结构 [英] union and structure

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

问题描述

大家好.
我是C ++的新手,试图弄清楚分配给strut的内存量.下面是代码:

Hi,all.
I am new to c++ and trying to figure out the amount of memory allocated to union to strut. Underneath is the code:

struct structure1
{
	int i;
	double d;
	char ch;
};

union Packed
{
        int i;
        double d;
        char ch;
}

int main(void)
{ 
        structure1 objstruct;
        Packed objP;
        std::cout<<sizeof(objstruct);
        std::cout<<sizeof(objP);
}


objstruct的输出大小不是其各自类型的算术加法,而是24.有人可以帮助解释原因吗?
对于联合而言,无论您拥有多少项目,它占用的内存始终是消耗最大内存量的类型的大小.在这种情况下,请加倍.
如何实现的?

预先谢谢您.


The output size of objstruct is not the arithmetic addition of its respective types, instead it is 24. Can someone help explain the reason?
For union, no matter how many items you have, the memory it occupies is always the size of the type which consume the maximum amount of memory. In this case, double.
How this is achieved?

Thank you in advance.

推荐答案

为什么要设置24个字节?这是3个8字节(64位)字的大小.您可能使用64位系统. int的大小取决于系统.不,结构尺寸不必一定是构件尺寸的总和.这取决于结构存储器的对齐方式,该对齐方式可能有所不同.通常按32位或64位边界使用对齐方式.例如,如果一个结构是64位对齐的,则如果一个成员需要64位而另外两个成员需要8位,则它将分配64 * 3位或24个字节.

关于第二个问题,这不是一个问题. 这是如何实现的"是什么意思?这不是实现"的,这是通过联合的定义来完成的.

-SA
Why 24 bytes? This is the size of 3 8-bytes (64-bit) words. You probably use 64-bit system. The size of int is system-dependent. And no, the structure size does not have to be the sum of the member sizes. It depends on structure memory alignment which can be different. Is is usual to use alignment by 32-bit or 64-bit boundary. For example, if a structure is 64-bit aligned, it will allocate 64*3 bits or 24 bytes if one member needs 64 bits and two other need 8 bits.

As to the second question, this is not a question. What do you mean by "How this is achieved?"? This is not "achieved", this is done by definition of the union.

—SA


它被称为:数据结构填充.
如果您通过以下方式更改结构成员的顺序:
It is called: Data structure padding.
If you change the order of structure members this way:
struct structure1
{
	int i;//4
	char ch;//1+3 (padding)
	double d;//8
};


-您将获得16个而不是24个.

这里对结构填充进行了足够好的说明: C语言中的结构填充


-you will get 16 instead of 24.

Here structure padding is explained good enough: Structure padding in C


本文非常详细地说明了这一点.很好: http://msdn.microsoft.com/en-us/library /2e70t5y1(v=vs.80).aspx [ ^ ]

This article explains this very nicely: http://msdn.microsoft.com/en-us/library/2e70t5y1(v=vs.80).aspx[^]

#pragma pack(push)   // Save setting
#pragma pack(1)      // 1 byte packing alignment for structure, 
                     // union, and class members.
struct stTest
{
    int i;
    double d;
    char ch;
};
#pragma pack(pop)    // Restore setting


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

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