Search code examples
cansi-c

Ansi C int16_t reference to int8_t array


I'm stuck with the above problem. Having an int8_t array:

int8_t i8array[3];
i8array[0] = 10;
i8array[1] = 15;
i8array[2] = 100;

And I want to not just convert but also reference an int16_t onto i8array[1]. So I want a new variable i16var, which is an int16_t with the value of 15<<8+100 = 3940.

And if I change i16var to 3941, it should change i8array's item#2 from 100 to 101.

Does ansi C has this facility? I had tried many things, and even in here, I just found answers for converting between these types.


Solution

  • Alignment and endian are the key issues. The below should handle the alignment issue, and maybe the endian one. Good luck. Do not advise the coding approach.

    int main(void) {
      union {
        struct {
          int8_t dummy;
          int8_t i8array[3];
        } view1;
        struct {
          int16_t dummy;
          int16_t i16var;
        } view2;
      } u;
    
      u.view1.i8array[0] = 10;
      u.view1.i8array[1] = 15;
      u.view1.i8array[2] = 100;
      printf("%d\n", htons(u.view2.i16var));
      u.view2.i16var = htons(3941);
      printf("%d\n", u.view1.i8array[2]);
      return 0;
    }
    

    Output

    3940
    101