--- In [email protected], Thomas Hruska <thru...@...> wrote:
> bobtransformer wrote:
> > ...I have a char array that is initialized to 128 bytes, say
> > like this...
> >
> > char myarray[128];
> >
> > Now, sometimes I want to re-use this array for ints and
> > shorts, and I know that it will be good for 64 shorts or
> > 32 int values.
You're making assumptions about the size of integer types.
Do you need to?
> > One method that comes to mind is a union, but I'm not
> > sure if that is the best way.
It is.
>
> You can reuse the array with typecasting but be sure to
> very carefully document it. You could use a pointer like:
>
> int *myarray_as_int = (int *)myarray;
The declaration of myarray above is not guaranteed to be
properly aligned for an int.
> A union would work as well (and perhaps better as your code
> might be more readable):
It would also be more robust with regard to alignment issues.
>
> union {
> char as_char[128];
> short int[64];
> int as_int[32];
> } myarray;
Better still IMO...
union myarray
{
unsigned char as_char[128];
short as_short[128 / sizeof(short)];
int as_int[128 / sizeof(int)];
} myarray;
But if you want to read 2 or 4 byte integers, you may be
better off simply reading 2 or 4 bytes from the character
array and constructing the integers.
--
Peter