CALCULATING THE SIZE OF STRUCTURE IN C/C++:
consider a strucure
struct X
{
short s;
int i;
char c;
};
what do you think the size of structure will be? 2 + 4 + 1 ?
Sorry, then you are wrong. Because to reduce the lookup time by CPU compiler pads up the bytes untill it becomes a multiple of 4. This is however dependent on hardware,but most compilers does so.
so what happens is
struct X
{
short s; /* 2 bytes */
/* 2 padding bytes */
int i; /* 4 bytes */
char c; /* 1 byte */
/* 3 padding bytes */
};
but this is not the best way to declare the struct , why? because you waste space due to padding of bytes. So here are some tricks to reduce the eat up of byte padding
struct Y
{
int i; /* 4 bytes */
char c; /* 1 byte */
/* 1 padding byte */
short s; /* 2 bytes */
};
struct Z
{
int i; /* 4 bytes */
short s; /* 2 bytes */
char c; /* 1 byte */
/* 1 padding byte */
};
POST YOUR DOUBTS IN THE COMMENTS
No comments:
Post a Comment