sizeof Struct

cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

sizeof Struct

897 Views
lpcware
NXP Employee
NXP Employee
Content originally posted in LPCWare by cesimkaol on Fri Jun 08 07:31:34 MST 2012
struct employer{

int yas;
char cinsiyet;
int boy;


};


struct employer1{

int yas;
int boy;
char cinsiyet;

};


int main()
{

    cout<<sizeof(employer)<<"--"<<sizeof(employer1)<<endl;

    return 0;
}

sizeof(int)=4;
sizeof(char)=1;

I thought result is 9 - 9 , but compailer give me a 12--12 ...

why that structs are both 12?
0 Kudos
Reply
3 Replies

850 Views
lpcware
NXP Employee
NXP Employee
Content originally posted in LPCWare by Ex-Zero on Fri Jun 08 09:48:17 MST 2012
Didn't we discuss the pros and cons of packed structs already :rolleyes:

http://knowledgebase.nxp.com/showthread.php?t=3260
0 Kudos
Reply

850 Views
lpcware
NXP Employee
NXP Employee
Content originally posted in LPCWare by frame on Fri Jun 08 09:16:01 MST 2012
I consider this struct layout as suboptimal.

struct employer
{
   int  yas;
   char  cinsiyet;
   int  boy;
};
Your second int variable happens to land on an odd address, if you really can force the compiler to pack it that dense.
But that means, the compiler would need to generate several additional instructions to read the misplaced/splattered [B][FONT=Courier New]int[/FONT][/B] into two registers, and merge it back into one variable. Most compiler refuse to do this for 32 bit machines.

Placing it that way:
struct employer
{
   int  yas;
   int  boy;
    char  cinsiyet;
 };
you have at least proper alignment inside of your struct.
0 Kudos
Reply

850 Views
lpcware
NXP Employee
NXP Employee
Content originally posted in LPCWare by TheFallGuy on Fri Jun 08 07:47:17 MST 2012

Quote:

why that structs are both 12?


Because the compiler will use 'natural' alignment by default. If you want something different, try packing the structure.
__attribute__((packed))
0 Kudos
Reply