Friday, June 09, 2006

Interesting C Question

A simple C question, What is the maximum size occupied by a structure? This question was asked by R* after reading some C books as a part of his placement preperation. The question is very very simple still i wanted to check how many are like me.

#include
int
main ()
{
struct simple
{
int a,b,d;
char c[2];
}tmpob;

int size;
size = sizeof (tmpob);
printf ("Total size of structure : %d\n",size);
return 0;
}

Predict the answer and give some explanation so that i may know the answer.

4 comments:

Senthil said...

take integer size as four and char as 1 as in the case of 32 bit systems. Now predict the answer.

Senthil said...

first i too thought it was 14. let me wait for one more day before telling the answer.

Ananth said...

As per your assumption of a 32 bit native int - the structure will occupy 16 bytes in memory. This is because, the instructions of all modern microprocessors need an address which is aligned to a multiple of their instruction set architechture size (4 bytes in this case).

This means that changing the char array c to c[1] or c[2] or c[3] or c[4] will have NO impact - the size will remain 16 bytes. Changing it to c[5] will make it 20 bytes and so on...

Caio,
Ananth

Senthil said...

ananth is right. No idea about what will happen in union.