Wednesday, July 19, 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.

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. (Address of every member of an union object is same.)


3. In other word, anytime you place a value in a union, the value always starts in
the same place at the beginning of the union, but only uses as much space as is necessary.
==

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; (only for C, I think)
typedef struct {
int data;
int text;
} S1;
// This will define a typedef for S1, in both C and in C++

struct S2 {
int data;
int text;
};

// This will define a typedef for S2. ONLY in C++, will create error in C.

struct {
int data;
int text;
} S3;
// This will declare S3 to be a variable of type struct.
// This is VERY different from the above two.
// This does not define a type. The above two defined type S1 and S2.
// This tells compiler to allocate memory for variable S3

void main()
{
S1 mine1; // this will work, S1 is a typedef.
S2 mine2; // this will work, S2 is also a typedef.
S3 mine3; // this will NOT work, S3 is not a typedef.
S1.data = 5; // Will give error because S1 is only a typedef.
S2.data = 5; // Will also give error because S2 is only a typedef.
S3.data = 5; // This will work, because S3 is a variable.
}

For linked list, the first 2 work:
typedef struct elementT{
int data;
struct elementT *next;
}element;

struct element2{
int data;
element2 *next;
};

typedef struct{
int data;
element3 *next;
}element3; // this will not work

No comments:

Post a Comment