On Mon, 6 Oct 2008 03:20:13 -0700 (PDT),
chang <ch************ ******@gmail.co mwrote:
Hi All,
have some experience in C prog language. I have small doubt abt
using unions in C language.
Here is a small programm in vc++:
union a{
int b;
char c;
}d;
int main () {
d.b=360;
d.c=1;
printf("%d %d ",d.b ,d.c,);
}
You can only access the value of the member you set last for a union.
So, if you set d.b, you can only read the value of d.b. Once you've
assigned something to d.c, you should no longer read the value of d.b
[1].
You also need to #include <stdio.hwhen you use printf().
Strictly speaking, the behaviour of the above program is undefined, and
therefore anything could happen.
In union largest sized member memory is reserved by union .
The size of the union is _at least_ the size of its largest member. It
can be larger.
but for a sake if i declare this way then i've seen the d.b value is
showing 257 in output window and if i declare d.b =255 or below 255
that then it is showing the what is last defined for d.c, means value
is =1 for all variables.
So Here for first time how the memory is overwritten?
Please let me know on this . I am looking forward to you .
next time, please simply write a program with inputs and outputs, rather
than trying to describe it in words. Programs and data are easier to
read and understand.
The members of a union share the same storage space. it is not entirely
clear from your post that you understand that. So, when you write to
one member, and then (incorrectly) access another member, the value that
you get back is potentially nonsensical. The system will try to
interpret the bit pattern in that location in a manner likely to be
incompatible with what was stored.
\begin{offtopic }
Assume your int is 16 bits (the same holds for a 32 bit int, but I don't
want to hape to type 16 extra zeroes.). The bit pattern for 360 would
be:
00000001:011010 00
Because your platform is little endian, that would live in memory like
this:
01101000:000000 01
Now you write to the char member of the union. The char is 8 bits, and
stored in the same _first_ 8 bits in the above pattern. You will store 1
in there, ending up with:
00000001:000000 01
Then you go and read this as an int again, ending up with the value 257.
Note that on a bigendian system the result will be wildly different,
which is one of the main reasons you need to not do this.
\end{offtopic}
Martien
[1] There are some special exceptions to this, but they do not apply
here.
--
|
Martien Verbruggen | Computers in the future may weigh no more
| than 1.5 tons. -- Popular Mechanics, 1949
|