Why does a structure consisting of char, short and char (in that order), when compiled in C ++ with 4-byte packaging enabled, come to a 6-byte structure?

I thought I understood how C / C ++ handles the alignment of structure elements. But I get strange results for a specific layout in Visual Studio 2008 and 2010.

In particular, I found that a structure consisting of char, short, and char was compiled into a 6-byte structure, even if 4- or 8-byte packaging was included. I am at a loss why this would be. I can understand the 4 byte structure. Perhaps I would understand an 8-byte structure. But I think that a 6-byte structure would not be possible if 4-byte packaging is included.

The program demonstrating the problem:

#include <iostream>
using namespace std;

#pragma pack (4)

struct Alignment
{
 char c1;
 short s;
 char c2;
};

#define REPORT_VAR_POSITION( structName, varName ) cout << "Member '" << #varName << "' sits at byte # " << offsetof( structName, varName ) << "." << endl;

int main(int argc, char* argv[])
{
 cout << "Sizeof struct Alignment is " << sizeof( Alignment ) << " bytes." << endl;
 REPORT_VAR_POSITION( Alignment, c1 );
 REPORT_VAR_POSITION( Alignment, s );
 REPORT_VAR_POSITION( Alignment, c2 );

 system( "pause" );

 return 0;
}

Conclusion:

Sizeof struct Alignment is 6 bytes.
Member 'c1' sits at byte # 0.
Member 's' sits at byte # 2.
Member 'c2' sits at byte # 4.
Press any key to continue . . .

- , VC ?

+5
3

MSDN #pragma pack ( n - , ):

, n, , , .

sizeof(short) - , , , short .

char (c2) , , Alignment , short . , , .

+16

-, . Visual Studio , . .

char ( 1 ) short ( 2 ), - 8- . , 2- . 6 .

, - , - 1- , short 2 1 4- .

+4

Visual Studio C /Zp [n], n -, #pragma pack, , n.

-1
source

All Articles