The correct way to access array elements as another type?

I have a large uint16_t array.

Most of its members are uint16_t , but some are int16_t and some are uint8_t .

How would you handle this?


By the way, I tried:

  • Pointers

    It uses 2 pointers, one int16_t* and the other uint8_t* , both of which are initialized at the beginning of the array, to access the array element int16_t and uint8_t .

    (This worked initially, but I ran into problems when something else later changed the meaning of pointers in the program, so I don't believe it.)

  • Type definition with union.

    In the .h file:

     typedef union { uint16_t u16[NO_OF_WORDS]; // As uint16_t int16_t s16[NO_OF_WORDS]; // As int16_t uint8_t u8[2 * NO_OF_WORDS]; // As uint8_t } ram_params_t; extern ram_params_t ram_params[]; 

    In file.c file:

     ram_params_t ram_params[] = {0}; 

    (It really bombed.)

  • Casting.

    (I'm not very far from this.)

+1
source share
2 answers

The problem with your attempt # 2 was that you created an array of arrays.

Or do the following:

 typedef union { uint16_t u16; // As uint16_t int16_t s16; // As int16_t uint8_t u8[2]; // As uint8_t } ram_params_t; extern ram_params_t ram_params[NO_OF_WORDS]; ram_params_t ram_params[NO_OF_WORDS]; uval16 = ram_params[i].u16; sval16 = ram_params[i].s16; uval8_1 = ram_params[i].u8[0]; uval8_2 = ram_params[i].u8[1]; 

Or you do it:

 typedef union { uint16_t u16[NO_OF_WORDS]; // As uint16_t int16_t s16[NO_OF_WORDS]; // As int16_t uint8_t u8[2 * NO_OF_WORDS]; // As uint8_t } ram_params_t; extern ram_params_t ram_params; ram_params_t ram_params; uval16 = ram_params.u16[i]; sval16 = ram_params.s16[i]; uval8_1 = ram_params.u8[2*i]; uval8_2 = ram_params.u8[2*i+1]; 

I do not see anything wrong with your attempt number 1. I think I will probably do it, and not using union.

+2
source

Other types of array elements must be the same size as uint16_t , so just drop them. In the case of 8-bit data, there is a possibility that the upper 8 bits will be undefined, so I hid them.

 #include <stdio.h> #define uint16_t unsigned short #define int16_t short #define uint8_t unsigned char int main() { uint16_t n; // convert uint16_t to int16_t n = 0xFFFF; printf ("%d\n", (int16_t)n); // convert uint16_t to uint8_t n = 168; printf ("%c\n", (uint8_t)(n & 0xFF)); return 0; } 

Program exit

 -1 ¿ 
+1
source

Source: https://habr.com/ru/post/978346/


All Articles