[gcc 4.4.3, ubuntu 10.04] Structure Padding

tukki's Avatar, Join Date: Aug 2010
Go4Expert Member
Hello Everyone. I need a little in understanding the padding of structures by a compiler.
The code is:
Code:
#include<stdio.h>

struct a{
int a;
char c; };

struct b{
char i;
char j; };

void main()
{
struct a a1;
struct b b1;

printf("a1: %d\n",sizeof(a1));
printf("a1.a: %d\n",sizeof(a1.a));
printf("a1.c: %d\n",sizeof(a1.c));

printf("b1: %d\n",sizeof(b1));
printf("b1.i: %d\n",sizeof(b1.i));
printf("b1.j: %d\n",sizeof(b1.j));
}
And here is the output:
Code:
a1: 8       //its of size 8 !!!
a1.a: 4    //while its members total upto 5 (4+1) !=8!
a1.c: 1    

b1: 2   //This here shows expected behaviour-> 2=1+1
b1.i: 1   
b1.j: 1
#1.> What are the rules for such padding.
#.> What is the arrangement of variables in the structure.

Thanks
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
Memory is something like a rectangular chunk and so you actually allocate it like this

int
0000
char
0---

the three --- for the ease of access

If you declare a float then the size of each variable will be of float.
0
xpi0t0s's Avatar, Join Date: Aug 2004
Mentor
Depends on the CPU. Some processors can't access multibyte types at all addresses so two-byte types need to be at even addresses, four-byte types at addresses divisible by 4 etc. Or they can but it takes longer because basically they can't so they get round that by doing two memory reads and swapping the bytes around. So the padding is added so that the CPU can address memory at addresses divisible by N. It's not something you normally need to worry about as a programmer as it's all handled automatically; the only time it's an issue is when you're poking around inside a padded structure with a pointer with a resolution of one byte, but there is very little need for that.
0
tukki's Avatar, Join Date: Aug 2010
Go4Expert Member
@shabbir: Thanks for replying.

@xpi0t0s: Thanks for replying.

I searched google and found some useful links, but am unable to post them here.

Thanks
0
shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
You will be able to post them after complete 10 posts and this has been done to stop spamming. Else you can edit the http and www part from the url and post them
0
tukki's Avatar, Join Date: Aug 2010
Go4Expert Member
@shabbir: Oh alright, here they are:
Link#1. //bytes.com/topic/c/answers/543879-what-structure-padding
link#2. //clinuxpro.com/Cprogramming/structurepadding.php

and one more thing--to control padding u can use #pragma directive specifically #pragma pack( ). Here is one rest can be found by google...
//publib.boulder.ibm.com/infocenter/macxhelp/v6v81/index.jsp?topic=/com.ibm.vacpp6m.doc/compiler/ref/rnpgpack.htm

Hope they are useful.
Thanks