If I understand what you are doing, then yes, you can access both bytes by casting to uint16_t , but at the same time you will encounter problems (or problems with endianess) with the way the byte order is stored in memory, and also violate strict smoothing. This will probably return an answer you did not suspect. For instance:
#include <stdio.h> #include <stdint.h> int main (void) { uint8_t array[] = {1,2,3,4}; uint8_t *p = array + 2; printf ("\n the uint8_t answer : %hhd\n", *p); printf (" the uint16_t answer : %hd\n\n", *(uint16_t *)p); printf ("**note: the will cast result in bytes 4, 3" " (or (4 << 8 | 3) = 1027)\n\n"); return 0; }
Output
$ ./bin/cast_array the uint8_t answer : 3 the uint16_t answer : 1027 **note: the cast will result in bytes 4, 3 (or (4 << 8 | 3) = 1027)
Bytes are stored in memory on my system in little endian order. Therefore, when clicking on uint16_t it expects to find the least significant , most significant bytes. Which in the above example with 34 in memory, cast will interpret the actual order as 43 , which will result in a value of 1027 instead of (3 << 8) | 4 = 772 (3 << 8) | 4 = 772 .
As already noted, you will break the rules associated with a strict alias, where trimming types by casting to anything other than char results in undefined behavior. The results of all these actions are hardware and compiler dependent and should not be used for anything other than training.
source share