Can I cast an unsigned char* to an unsigned int*?

David Mulder picture David Mulder · Mar 31, 2014 · Viewed 7.5k times · Source
error: invalid static_cast from type ‘unsigned char*’ to type ‘uint32_t* {aka unsigned int*}’
     uint32_t *starti = static_cast<uint32_t*>(&memory[164]);

I've allocated an array of chars, and I want to read 4 bytes as a 32bit int, but I get a compiler error. I know that I can bit shift, like this:

(start[0] << 24) + (start[1] << 16) + (start[2] << 8) + start[3];

And it will do the same thing, but this is a lot of extra work.

Is it possible to just cast those four bytes as an int somehow?

Answer

user2033018 picture user2033018 · Mar 31, 2014

static_cast is meant to be used for "well-behaved" casts, such as double -> int. You must use reinterpret_cast:

uint32_t *starti = reinterpret_cast<uint32_t*>(&memory[164]);

Or, if you are up to it, C-style casts:

uint32_t *starti = (uint32_t*)&memory[164];