bobtransformer wrote:
> Hi, and thank you for the help on my "expected an expression" problem from 
> this weekend.  It now works !!
> 
> So, I am trying to use memory very sparingly in my embedded system, as I 
> always try to do.
> 
> 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.  I cannot just 
> type-cast  like this:  (int) myarray[2] = 123456;  for instance.
> 
> What is the best way to use this existing allocated memory for all 3 types of 
> data ??  I do not need to convert int data to char or anything like that.  I 
> just want to use the array for the different types at different times in the 
> program. This array is only temporary storage for reading and writing data to 
> and from an EEprom.
> 
> One method that comes to mind is a union, but I'm not sure if that is the 
> best way.
> 
> Ideas ??
> 
> Thank you again  !
> boB

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;

Then access the array with myarray_as_int when you want to store ints.

A union would work as well (and perhaps better as your code might be 
more readable):

union {
   char as_char[128];
   short int[64];
   int as_int[32];
} myarray;

myarray.as_int[2];

-- 
Thomas Hruska
CubicleSoft President
Ph: 517-803-4197

*NEW* MyTaskFocus 1.1
Get on task.  Stay on task.

http://www.CubicleSoft.com/MyTaskFocus/

Reply via email to