Struct的大小不等于每个成员的总大小吗? [英] Size of a Struct does not equal to total size of each member?

查看:57
本文介绍了Struct的大小不等于每个成员的总大小吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下来源检查结构的大小.

I have this following source to check size of a struct.

struct com_msg1	{
	short	length; 			/* message length	*/
};

struct com_msg2	{
	void	(*function)();			/* com out func address */
};
struct com_msg3	{
	short	length; 			/* message length	*/
	void	(*function)();			/* com out func address */
};


void main()
{
	cout << "Size of C_MSG1: " << sizeof(com_msg1) << endl;
	cout << "Size of C_MSG2: " << sizeof(com_msg2) << endl;
	cout << "Size of C_MSG3: " << sizeof(com_msg3) << endl;
}



输出为:



and output is:

Size of C_MSG1: 2
Size of C_MSG2: 4 
Size of C_MSG3: 8



这对我来说很奇怪,第三个结构的大小不等于两个第一个结构的总和.

您能解释一下吗?



this is strange for me that size of 3rd struct does not equal to total of two first structs.

Could you please explain this?

推荐答案

这是一个常见问题解答.编译器正在根据结构对齐设置调整结构成员的偏移量.如果成员不在对齐的地址处,则编译器将插入填充字节.

对于MS编译器,您可以使用编译器选项/Zp设置全局对齐方式,并在使用#pragma pack()指令声明后针对特定结构调整对齐方式.
This is a FAQ. Compilers are adjusting struct member offsets according to the struct alignment setting. If a member would be not at an aligned address, the compiler inserts padding bytes.

With MS compilers, you can set the global alignment with compiler option /Zp and adjust the alignment for specific structs upon declaration using the #pragma pack() directives.


有一种称为打包对齐的内容适用于结构,工会和班级成员.可以使用#pragma指令为编译器指定此对齐方式.

现在,对于您的编译器,我想默认的打包对齐方式是4.因此,一旦4个字节用完,编译器将使用4个字节,而不是成员的确切大小.

修改填料排列时应格外小心,因为这可能会影响性能.

现在是带有成员的结构

There is something called packing alignment which is applied for structure, union, and class members. This alignment can be specified to the compiler by using #pragma instruct.

Now for your compiler I guess the default packing alignment is 4. So once that 4 bytes are exhausted, then the compiler will go for 4 bytes instead of the exact size of the member.

One should be careful while modifying packing alignment as this may effect performance.

Now a struct with members

#pragma pack(4)
struct A
{
   short m_s1;
   int* m_pi;
   short m_s2;
};

void main()
{
     A obj;
     size_t s = sizeof(obj);
}



这里的sizeof(obj)是12.现在,我们可以通过更改结构成员的顺序将其减少到8个字节



Here sizeof(obj) is 12. Now we can reduce this to 8 bytes by changing the order of structure members

struct A
{
   short m_s1;
   short m_s2;
   int* m_pi;
};


非常感谢您的答复.
感谢您的回答,我已经在以下网址阅读了有关"Struct Aligment"的信息:
http://msdn.microsoft.com/en-us/library/71kf49f1 (v = vs.80).aspx [
Thanks for you very quick answer.
Thank to ur answer, I have read about "Struct Aligment" at:
http://msdn.microsoft.com/en-us/library/71kf49f1(v=vs.80).aspx[^]

my answer is closed now.


这篇关于Struct的大小不等于每个成员的总大小吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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