A quick question...
Dan Bernstein
brnstnd at kramden.acf.nyu.edu
Tue Mar 12 19:03:34 AEST 1991
In article <1991Mar12.030759.26698 at nntp-server.caltech.edu> eychaner at suncub.bbso.caltech.edu writes:
> unsigned char *pointer1;
> short short_value;
The value that ``pointer1'' refers to has not yet been defined. It's
probably garbage.
> ...
> *((short *) pointer1) = short_value;
If ... doesn't include any initialization of pointer1, this has
undefined behavior.
If ... initializes pointer1 to point to some memory location other than
that occupied by a short, your code sequence has undefined behavior.
If ... initializes pointer1 to point to the memory occupied by a short,
then this will work. You can cast freely between char *, void *, and any
(single) other pointer-to-object type. This would work:
char *pointer1;
short foo;
short bar;
...
pointer1 = (char *) &foo;
*((short *) pointer1) = bar;
This has the same effect as foo = bar. I believe unsigned char * works
the same as char * for this purpose.
> And does it do what I think it does, that is, assign short_value to the
> storage pointed to by pointer1?
Only if you've set pointer1 to point to some valid short storage. (Of
course, you need to initialize short_value as well.)
---Dan
More information about the Comp.lang.c
mailing list