A quick question...
Amateurgrammer
eychaner at suncub.bbso.caltech.edu
Tue Mar 12 16:29:41 AEST 1991
eychaner at suncub.bbso.caltech.edu (Amateurgrammer) writes:
*Note* A followup question follows....
>Is this legal...
> unsigned char *pointer1;
> short short_value;
> ...
> *((short *) pointer1) = short_value;
> ...
>And does it do what I think it does, that is, assign short_value to the
>storage pointed to by pointer1? I hope you understand what I mean...
> -Glenn
Summary so far: In short, yes it is legal. However:
1) pointer1 must point to something large enough to hold a short. Duh. :-)
2) Unless pointer1 is something like:
pointer1 = (unsigned char *) (&something_short);
alignment problems may result on some machines. I figured that.
3) The exact effect is not machine portable (depending on your machine's
order of storage for short, I guess).
Followup question:
The reason for this is I am writing a subroutine which stores some values
in an array of short OR unsigned char. I thought the solution would be:
(this is a HIGHLY simplified version; the real routine is complex enough
that I don't need two nearly identical copies floating about...)
int do_array (void *array, int size, int type)
{
unsigned char *arrayptr;
int i;
arrayptr = array; /* If only void * arithmetic were legal in VAX C */
for (i = 0; i < size; i++) {
if (type == UNSIGNED_CHAR) {
/* My precedence rules say this is right */
*arrayptr++ = some_value(); /* Declared properly elsewhere */
}
else if (type == SHORT) {
/* My precedence rules ALSO say THIS is right */
*(short *)arrayptr++ = othervalue(); /* Declared elsewhere */
}
}
}
******************************************************************************
Glenn Eychaner - Big Bear Solar Observatory - eychaner at suncub.bbso.caltech.edu
"...this morning's unprecedented solar eclipse is no cause for alarm."
-_Flash Gordon_
More information about the Comp.lang.c
mailing list