Is there a way in C/C++ to cast a char array to an int at any position?
I tried the following, bit it automatically aligns to the nearest 32 bits (on a 32 bit architecture) if I try to use pointer arithmetic with non-const offsets:
unsigned char data[8];
data[0] = 0; data[1] = 1; ... data[7] = 7;
int32_t p = 3;
int32_t d1 = *((int*)(data+3)); // = 0x03040506 CORRECT
int32_t d2 = *((int*)(data+p)); // = 0x00010203 WRONG
Update:
My main questions at the moment are: Why has d1 the correct value but d2 does not? Is this also true for other compilers? Can this behavior be changed?
No you can't do that in a portable way.
The behaviour encountered when attempting a cast from char*
to int*
is undefined in both C and C++ (possibly for the very reasons that you've spotted: int
s are possibly aligned on 4 byte boundaries and data
is, of course, contiguous.)
(The fact that data+3
works but data+p
doesn't is possibly due to to compile time vs. runtime evaluation.)
Also note that the signed-ness of char
is not specified in either C or C++ so you should use signed char
or unsigned char
if you're writing code like this.
Your best bet is to use bitwise shift operators (>>
and <<
) and logical |
and &
to absorb char
values into an int
. Also consider using int32_t
in case you build to targets with 16 or 64 bit int
s.