Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

emilbbb

A structure size problem

This topic is 5562 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Here is my code:
#include <iostream.h>

struct Test
{
	int v1;
	short v2;
	char v3;
};

int main()
{
	Test test;

	cout << "Int: " << sizeof(int) << " bytes\nShort: " << sizeof(short) << " bytes\nChar: " << sizeof(char) << " bytes\n----------" << endl;//" " << sizeof(char) << " " << sizeof(char) << endl;

	cout << "Test.v1: " << sizeof(test.v1) << " bytes\nTest.v2: " << sizeof(test.v2) << " bytes\nTest.v3: " << sizeof(test.v3) << " bytes\n----------" << endl;// " " << sizeof(test.v4) << " " << sizeof(test.v5) << endl;

	cout << "test: " << sizeof(test) << " bytes\nTest: " << sizeof(Test) << " bytes" << endl;

	return 0;
}
And the output i get is: Int: 4 bytes Short: 2 bytes Char: 1 bytes ---------- Test.v1: 4 bytes Test.v2: 2 bytes Test.v3: 1 bytes ---------- test: 8 bytes Test: 8 bytes Why does it say that the structure Test is 8 bytes when v1+v2+v3 is only 7 bytes? I have tested some other structures too. If I use this structure:
struct Test
{
	int v1;
	short v2;
	char v3;
	char v4;
};
it says that the size is 8 bytes which is correct but if I use this structure:
struct Test
{
	int v1;
	short v2;
	char v3;
	char v4;
	char v5;
};
it says that the size is 12 bytes which is not correct. I have tested to compile the program on different compilers but they all return the same wrong result. Does anyone know why it returns the wrong size of the structure? [edited by - emilbbb on September 23, 2003 11:18:27 AM]

Share this post


Link to post
Share on other sites
Advertisement
Heh The compiler is padding the struct to memory-align it as memory-alignement will make it faster.

I think (if you''re using Visual C++) you can use:


#pragma push(pack,1) //At the start of struct declarations
#pragma pop //At the end of struct declarations


to get the correct sizes.

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!