Monday, July 27, 2009

What is the difference b/w structure and uniom? answer the below Qs?

1. Struct x


{


int i;


char c;


}





union y{


struct x a;


double d;


};





printf("%d",sizeof(union y));





a)8


b)5


c)4


d)1











explain ur answers ?

What is the difference b/w structure and uniom? answer the below Qs?
A union is essentially a structure in which all of the fields overlay each other; you can only use one field at a time. (You can also cheat by writing to one field and reading from another, to inspect a type's bit patterns or interpret them differently, but that's obviously pretty machine-dependent.) The size of a union is the maximum of the sizes of its individual members, while the size of a structure is the sum of the sizes of its members.
Reply:The answer is pegasus.
Reply:From the web:


Unions are like structures except that all members of a union have a zero offset from the beginning of the union. In other words, the members overlap. Unions are a way to store different type of objects in the same memory location.





--------------------------------------...


And the answer to your question is 8


Size of union = size of largest element in the same = size of struct





As to size of struct, even though it appears at 1st look to be that the size should be 5, we need to understand that most compilers do some basic optimization and allocating memory in blocks of 4 every data type less than or equal to 4 bytes is the norm for a structure.





I am avoiding getting into a discussion on how an int may not be 4 bytes in each OS. Lets just say that on most OS today, it happens to be 4 bytes!





So size of struct = 8 bytes.


Hence size of union = 8 bytes

survey for money

No comments:

Post a Comment