Electronic – Char array at an int in C18

cc18mplabpicsoftware

In Jal, it's possible to do something like this:

var word the_var = 0x1234
var byte the_array[2] at the_var;

Now you can easily access the bytes of the word the_var with the_array[0] (0x34) and the_array[1] (0x12). Can something similar be done with the C18 compiler?

I have an unsigned int the_var and want to access the separate chars in that variable using an array.

Best Answer

One C equivalent is to use a anonymous union, there are a few ways to use them so it's worth researching them further but an example is:

static union {
  word the_var;
  byte the_array[2];
};
the_var = 0x1234;
some_value = the_array[0];
some_other_value = the_array[1];

Another way to go about it is to use a pointer to the value:

word the_var = 0x1234;
byte *the_array = (byte *) &the_var;
some_value = the_array[0];
some_other_value = the_array[1];