简体   繁体   English

在 C 中将 char_array 类型转换为 unsigned int

[英]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;如果我有一个 4 字节大小的 char 数组,并且我尝试将他转换为无符号整数(4 字节),编译器会给我一个错误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?如果两个变量的大小都是 4 个字节,为什么要给我这个错误?

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.您不能按值分配 arrays 因为它们被转换为第一个元素的地址。 Your code is equivalent to:您的代码相当于:

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

Use memcpy instead:请改用memcpy

_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')变量“char_array”是指向 memory 区域的指针(包含 4 个字节:“a”、“b”、“c”、“d”)

so the value itself of char_array is not abcd but 0x[memory addr].所以char_array的值本身不是abcd而是0x[memory addr]。

If your cast with (unsigned int), the value of your no_pointer will be 0x[memory addr]如果您使用 (unsigned int) 进行强制转换,则 no_pointer 的值将为 0x[memory addr]

So two solutions: if you want a unsigned int pointer to abcd then you need:所以有两个解决方案:如果你想要一个指向 abcd 的 unsigned int 指针,那么你需要:

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:如果你想直接在 integer 变量中的值 abcd 你需要取消引用指针:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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