Tuesday, July 18, 2006

difference between structure and union

The difference between structure and union in c are:
1. union allocates the memory equal to the maximum memory required by the member of the union but structure allocates the memory equal to the total memory required by the members (also thinking of alignment).
2. In union, one block is used by all the member of the union but in case of structure, each member have their own memory space. While structure enables us treat a number of different variables stored at different in memory , a union enables us to treat the same space in memory as a number of different variables. That is a Union offers a way for a section of memory to be treated as a variable of one type on one occasion and as a different variable of a different type on another occasion.

What's the difference between these two declarations?
 struct x1 { ... };
typedef struct { ... } x2;

The first form declares a structure tag; the second declares a typedef.
The main difference is that the second declaration is of a slightly more abstract type--its users don't necessarily know that it is a structure, and the keyword struct is not used when declaring instances of it:
x2 b;
Structures declared with tags, on the other hand, must be defined with
struct x1 a;
(check another post day after this)

No comments:

Post a Comment