The size of the structure and the corresponding variable

If I define a char variable

char a;

and single-member char structure

struct OneChar {
char a;
};

Will both of these definitions be "char" in all compilers? My doubt is that if we define a char variable in a structure, due to memory packing, will it have a larger size than the char size?

+3
source share
6 answers

It depends on the architecture and the compiler. In this particular case, you should be safe, but see Laying the data structure .

Here's an excerpt :

Typical alignment of C structures on x86

, Data1 Data2 Data2 Data3:

struct MyData
{
    short Data1;
    short Data2;
    short Data3;
};

"" , , 2 . Data1 0, Data2 2 Data3 4. 6 .

, , , . Microsoft, Borland GNU 32- x86:

  • A char ( ) 1 .
  • ( ) 2 .
  • int ( ) 4 .
  • ( ) 4 .
  • ( ) 8-, Windows 4-, Linux.

, 8 :

struct MixedData
{
    char Data1;
    short Data2;
    int Data3;
    char Data4;
};

, :

struct MixedData  /* after compilation */
{
    char Data1;
    char Padding0[1]; /* For the following 'short' to be aligned on a 2 byte boundary */
    short Data2;
    int Data3;  
    char Data4;
    char Padding1[3];
};

12 . , . 3 .

( ) ( "" ) .

, MixedData .

, #pragma . :

#pragma pack(push)  /* push current alignment to stack */
#pragma pack(1)     /* set alignment to 1 byte boundary */

struct MyPackedData
{
    char Data1;
    long Data2;
    char Data3;
};

#pragma pack(pop)   /* restore original alignment from stack */

6 . Microsoft, Borland, GNU .

+6

, , .

+1

, , 1- ABI, .

, sizeof(struct OneChar) , :

(char*)&(((struct OneChar*)0)->a) - (char*)0
+1

a , , .

, , ... "" .

0

, . - :

void fun()
{
    char c;
    int n;
}

, . , , , .

0

. , , - , . .

, Visual Studio #pragma pack .

0

Source: https://habr.com/ru/post/1719642/


All Articles