struct X
char ch;
int i;
char a ;
char b;
long l;

First the compiler allots a 4-byte location to the char variable ch .

Can you tell me why the compiler will allocate 4-bytes to char in this structure ? how this padding concept will work?


ANSWER: The C/C++ Standards define alignment as a "requirement that objects of a particular type be located on storage boundaries with addresses that are particular multiples of a byte address". The Standard leaves it up to each target processor to specify its alignment requirements.

For example, a processor might require that a 4-byte integer be aligned at an address that's a multiple of four. A processor also might require that an 8-byte floating-point number be aligned at an address that's a multiple of eight.

Compilers may insert unused bytes called padding bytes after certain structure members to ensure that the next  member is correctly aligned meeting the alignment requirements for that object on the target processor.

In the above example, the compiler does not allocate four bytes to the char member - sizeof(char) is one byte by definition and only one byte is allocated. But the int member needs to be aligned on an address that is a multiple of four-bytes. To meet this alignment requirement, three bytes of padding are added after the first char member.

For more information see:

---------- FOLLOW-UP ----------

QUESTION: I got one more doubt on this, how can i know its 2-byte or 4-byte or 8-byte alignmented so that rearranging or propre arrange of structure members reduce the memory usage. In the above structure it have int,long which are 4-bytes so its doing 4-byte alignment? if it have double which is 8-byte it will be 8-byte allignment ?

or how i can know the particular processor allignment? for For 32-bit(4-byte alignment) and 64-bit(8-byte alignment)

please clarify me on this, i got bit confuse on it


C++03 provides no standard keyword or function for querying the alignment requirements of types. However, because knowing this is sometimes useful, almost every implementation provides an extension by using an implementation-defined keyword for this purpose.

For example, microsoft C++ has the __alignof operator : http://msdn.microsoft.com/en-us/library/45t0s5f4.aspx

GCC provides __alignof__

with some advanced knowledge, it is possible to write an alignof macro that would be portable.
see: http://www.wambold.com/Martin/writings/alignof.html

Thye upcoming C++0x standard has added functionality to query and control alignment to the core language.
see: http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=405


All Answers

Answers by Expert:

Ask Experts




my primary areas of interest are generic and template metaprogramming, STL, algorithms, design patterns and c++11. i would not answer questions about gui and web programming.


about 15 years or so

post graduate engineer

©2016 About.com. All rights reserved.