Tags

, , ,

Suppose we have struct like this.

struct
{
double dVal;
int nVal;
char chVal;
} Data1;

So what will be the size of Data1?
We think like
sizeof(char) + sizeof(int) + sizeof(double) = 13. Is it?

But Surprisingly we are wrong.

Again look at another struct like this.


struct
{
int nVal;
char chVal;
char chVal2;
double dVal;
} Data2;

We think like
sizeof(char) + sizeof(char) + sizeof(int) + sizeof(double) = 14. Is it?

In both cases, sizeof(Data1) and sizeof(Data2) will be 16. how?

So, struct stores its variables in different way. Let’s discuss.

1. struct allocate memory for its first variable as same as the most longest variable used in that struct. Here double is most longest. so, it will allocated 8bytes for the first variable.

2. Then come for the second variable. It checks the size of the data type of the second variable. If already allocated memory for first variable, is enough then struct doesn’t allocate new memory. Otherwise, allocate big size like first variable.

Now discuss about our example.

struct Data1
1. For double it will allocate 8bytes,
2. For int, it will also allocated 8bytes.
3. For char, I won’t allocate any, because already 4bytes is extra from int type.

struct Data2
1. for int datatype it will allocate 8bytes, as double needs 8bytes.
2. for char it will need 1byte. As Data2 have already 4bytes extra, so no need to allocate for next two char.
3. Now Data2 have 2 bytes extra, but double needs 8bytes. So, 8 bytes will be allocated.

I think we all are clear now.

Advertisements