简体   繁体   中英

Type Cast char_array to unsigned int in C

If i have a char array of 4 bytes in size and i try to cast him into a unsigned int(4 bytes too), the compiler give me an error warning: cast from pointer to integer of different size [-Wpointer-to-int-cast] no_pointer = (unsigned int) char_array; Why give me this error if both variables have 4 bytes in size?

Code:

char char_array[4] = {'a', 'b', 'c', 'd'};
unsigned int no_pointer;
no_pointer = (unsigned int) char_array;

You cannot assing arrays by value because they get converted to address to first element. Your code is equivalent to:

no_pointer = (unsigned int) &char_array[0];

Use memcpy instead:

_Static_assert(sizeof no_pointer == sizeof char_array, "Size mismatch"); // Extra safety check to make sure that size match
memcpy(&no_pointer, char_array, sizeof no_pointer);

But please keep in mind that byte order is dependent on endianness when using this approach.

the variable 'char_array' is a pointer to a memory zone (containing 4 bytes: 'a', 'b', 'c', 'd')

so the value itself of char_array is not abcd but 0x[memory addr].

If your cast with (unsigned int), the value of your no_pointer will be 0x[memory addr]

So two solutions: if you want a unsigned int pointer to abcd then you need:

unsigned int *no_pointer;
no_pointer = (unsigned int *)char_array

If you want the value abcd directly in the integer variable you need to dereference the pointer:

unsigned int no_pointer;
no_pointer = *(unsigned int *)char_array;

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