Question on sizeof struct

Looking at this code:

1
2
3
4
5
6
7
struct test
{
	char c; // 1 byte
	int i;  // 4 bytes
}sample1, sample2;

cout << sizeof(sample1);


Outputs 8 bytes. Why is it 8 instead of 5?

I'm no expert in this matter, but it is my understanding that compilers tend to pad structures to a "nicer" number of bytes because the underlying architecture performs faster. 5 bytes is definitely not good, but 8 is a perfect multiple for the 32-bit architecture your software runs on.
Yes, that is why.

Your compiler should give you a compiler-specific means by which to change the alignment of elements within the structure at the time of declaration if you need the elements to not be
word-aligned.
Any idea how to accomplish this in MSVC++? My searches haven't turned up much.
The pragma preprocessor command can be used to pack things to byte boundaries. Anything you attempt to do to change the packing would have to be done with precompiler directives that are environment specific. Different compilers have different rules for packing.


EDIT
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#pragma pack(1)
struct test
{
	char c; // 1 byte
	int i;  // 4 bytes
}sample1, sample2;
#pragma pack

// Here is a complete function that compiles
int main()
{
    std::cout << "sizeof(sample1)" << sizeof(sample1) << std::endl;
    return 0;
}

I found this with a simple google search. Here is MSDN's page. Just make sure that you read the warnings carefully. After you manually pack, there are sometimes alignment problems that can be tricky to understand. I don't fully understand the issues myself.
http://msdn.microsoft.com/en-us/library/2e70t5y1(VS.80).aspx
Last edited on
Topic archived. No new replies allowed.