简体   繁体   中英

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

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?

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];

Yes, you can convert an unsigned char* pointer value to uint32_t* (using either a C-style cast or a reinterpret_cast ) -- but that doesn't mean you can necessarily use the result.

The result of such a conversion might not point to an address that's properly aligned to hold a uint32_t object. For example, an unsigned char* might point to an odd address; if uint32_t requires even alignment, you'll have undefined behavior when you try to dereference the result.

If you can guarantee somehow that the unsigned char* does point to a properly aligned address, you should be ok.

I am used to BDS2006 C++ but anyway this should work fine on other compilers too

char memory[164];
int *p0,*p1,*p2;
p0=((int*)((void*)(memory)));    // p0 starts from start
p1=((int*)((void*)(memory+64))); // p1 starts from 64th char
p2=((int*)((void*)(&memory[64]))); // p2 starts from 64th char

You can use reinterpret_cast as suggested by faranwath but please understand the risk of going that route.

The value of what you get back will be radically different in a little endian system vs a big endian system. Your method will work in both cases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM