How to avoid slack byte Problem? Padding problem in structure

How to avoid slack problem?Padding problem
Example:-
If structure is like this below
struct word1
{
char a;
int b;
char c;
};

it has slack(padding) byte as below


To avoid it structure should be rearranged as example 2
strcut word2
{
char a;
char b;
int c;

};

First of all char a will reserve two byte and store the data in only first byte .Now char b will search one byte and one byte is available so it will store the data in that byte. Now int c will reserve two byte and store the data in both two bytes. Now there is not any slack byte and we have saved wastage of memory and structure word2 is balance.

(Before executing this program first go to option menu then compiler then code generation then select word alignment then press OK)

Program:

void main()
{
struct word1
{
char a;
int b;
char c;
} ;
struct word2
{
char a;
char b;
int c;
};
clrscr();
printf("%d\t%d",sizeof(struct word1),sizeof(struct word2));

getch();
}
Output: 6 4

No comments:

 
Top Blogs