csudha said:
Hi All,
Can you give me the example code which explains difference between
Structures and Union. As a newbie please do the needful.
struct foo
{
char c;
long l;
char *p;
};
union bar
{
char c;
long l;
char *p;
};
A struct foo contains all of the elements c, l, and p. Each element is
separate and distinct.
A union bar contains only one of the elements c, l, and p at any given
time. Each element is stored in the same memory location (well, they all
start at the same memory location), and you can only refer to the element
which was last stored. (ie: after "barptr->c = 2;" you cannot reference
any of the other elements, such as "barptr->p" without invoking undefined
behavior.)
Try the following program. (Yes, I know it invokes the above-mentioned
"undefined behavior", but most likely will give some sort of output on
most computers.)
==========
#include <stdio.h>
struct foo
{
char c;
long l;
char *p;
};
union bar
{
char c;
long l;
char *p;
};
int main(int argc,char *argv[])
{
struct foo myfoo;
union bar mybar;
myfoo.c = 1;
myfoo.l = 2L;
myfoo.p = "This is myfoo";
mybar.c = 1;
mybar.l = 2L;
mybar.p = "This is mybar";
printf("myfoo: %d %ld %s\n",myfoo.c,myfoo.l,myfoo.p);
printf("mybar: %d %ld %s\n",mybar.c,mybar.l,mybar.p);
return 0;
}
==========
On my system, I get:
myfoo: 1 2 This is myfoo
mybar: 100 4197476 This is mybar
Note how all of the "myfoo" elements are intact, whereas only the
"mybar.p" entry is intact, as the others have been overwritten by the
assignment to mybar.p.