你如何在 c 中的一行中进行类型转换?
how do you do a type casting in one line in c?
如何在 c 中的一行中进行类型转换?
unsigned char num[4]={0,2}; //512 little endian
unsigned int * ptr = num;
printf("%u\n", *ptr); // 512
//trying to do the same underneath in one line but it dosen't work
printf("%u\n", (unsigned int *)num); //
同
unsigned int * ptr = num; printf("%u\n", *ptr); // !! nonportable, nonsafe (UB-invoking)
在一行中是
printf("%u\n", *(unsigned int *)num); // !! nonportable, nonsafe (UB-invoking)
然而,这两个版本都不可移植且不安全。他们通过违反严格的别名规则并可能通过创建未适当对齐的指针来调用未定义的行为。
您可以使用 memcpy 安全地完成此操作:
#include <stdio.h>
#include <string.h>
int main(){
unsigned char num[4]={0,2}; //512 little endian
#if 0
//the unsafe versions
unsigned int * ptr = num; printf("%u\n", *ptr);
printf("%u\n", *(unsigned int *)num);
#endif
//the safe version using a compound literal as an anonymous temporary;
//utilizes how memcpy returns the destination address
printf("%u\n",*(unsigned*){memcpy(&(unsigned){0},&num,sizeof(num))});
}
如何在 c 中的一行中进行类型转换?
unsigned char num[4]={0,2}; //512 little endian
unsigned int * ptr = num;
printf("%u\n", *ptr); // 512
//trying to do the same underneath in one line but it dosen't work
printf("%u\n", (unsigned int *)num); //
同
unsigned int * ptr = num; printf("%u\n", *ptr); // !! nonportable, nonsafe (UB-invoking)
在一行中是
printf("%u\n", *(unsigned int *)num); // !! nonportable, nonsafe (UB-invoking)
然而,这两个版本都不可移植且不安全。他们通过违反严格的别名规则并可能通过创建未适当对齐的指针来调用未定义的行为。
您可以使用 memcpy 安全地完成此操作:
#include <stdio.h>
#include <string.h>
int main(){
unsigned char num[4]={0,2}; //512 little endian
#if 0
//the unsafe versions
unsigned int * ptr = num; printf("%u\n", *ptr);
printf("%u\n", *(unsigned int *)num);
#endif
//the safe version using a compound literal as an anonymous temporary;
//utilizes how memcpy returns the destination address
printf("%u\n",*(unsigned*){memcpy(&(unsigned){0},&num,sizeof(num))});
}