Computer Forums

Member Login

Remember Me? Sign Up! | Forgot Password
 
Slogan
 
Closed Thread
Old 04-23-2005, 03:06 PM   #1 (permalink)
 
True Techie

Join Date: Dec 2004

Posts: 145

Mohan Giri

Default Structure Vs Union

What is the difference between structure and union?? Where we use structure data type and where we use union data type?
Mohan Giri is offline  
Old 06-13-2005, 01:15 AM   #2 (permalink)
 
Newb Techie

Join Date: Jun 2005

Posts: 18

warrior1981

Default

a structure and a union differs in the memory allocation
a union takes the highest type of the variable allocated.
for example....
union u1{
int rolno;
char name;
};

then the maximum abt of memory will be that as the size of the integer....

but in the case of the structure,
struct s2{
int rollno;
char name;
};
the memory allocation will be that of a char and a int
thats the plain difference between the two.....
warrior1981 is offline  
Old 06-13-2005, 04:07 AM   #3 (permalink)
Chankama's Avatar
 
Monster Techie

Join Date: Jan 2005

Location: Canada

Posts: 1,522

Chankama will become famous soon enough

Default

Warrior is right. If it wasn't clear, with a structure, what he meant was that the total memory allocated will be sizeof(int) + sizeof(char)..

In anycase, why are unions useful?.. Well, one application would be if u want to easily "go through" a variable. For example, in the example above, if the "int" has a particular value that u had set, using a "char" array variable would allow u to obtain a byte from the int without having to worry about bit shifting/masking/pointers and such..
Chankama is offline  
 
Closed Thread

« Vb | hi guys »
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are On