Click here to Skip to main content
15,900,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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:

CSS
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?
Posted

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.
 
Share this answer
 
v3
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

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

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


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

C++
struct A
{
   short m_s1;
   short m_s2;
   int* m_pi;
};
 
Share this answer
 
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.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900