Timur Fayzrakhmanov Timur Fayzrakhmanov - 19 days ago 5
C Question

How to iterate over array interpreting its element as different type?

There is an

arr
array with allocated memory for two
short
s (4 bytes in total). Then I fill these two elements with
ffff
and
eeee
accordingly. After I'm trying to iterate over the same allocated memory as it was allocated for 4
char
s (also 4 bytes in total, but now I suppose be able to look up elements by 1 byte). As you can see from the output it doesn't show what I expect (get the same
0xeeeeffff
splitted to 4 separate elements). What's wrong with the code?

short *arr = malloc(sizeof(short) * 2);
*arr = 0xeeee;
*(arr + 1) = 0xffff;
printf("%p\n", &arr[0]);
printf("%p\n", &arr[1]);
// convert
char * cnv = (char *)arr;
printf("=======\n");
for (int i = 0; i < 4; i++) {
printf("%p\n", cnv);
printf("%x\n", *cnv);
cnv++;
}


The output:

0x759010
0x759012
=======
0x759010
ffffffee # expect 'ee'
0x759011
ffffffee # expect 'ee'
0x759012
ffffffff # expect 'ff'
0x759013
ffffffff # expect 'ff'

Answer

%x expects an unsigned int, not a char, and thus your program has undefined behaviour. You need %hhx.