请问指针类型转换和强制类型转换的区别在哪里呢
请问指针类型转换和强制类型转换的区别在哪里呢为什么代码1的结果和代码2的结果不一样呢?原理是什么
代码1
long ua { 1000 }; long long* uptr { (long long*)&ua }; std::cout << *uptr;
代码2
long ua { 1000 }; long long uptr { (long long) ua }; std::cout << uptr;
```
long ua { 1000 }; long long* uptr { (long long*)&ua }; std::cout << *uptr;
long ua { 1000 }; long long uptr { (long long) ua }; std::cout << uptr;
#include <cstdio> #include <cstdint> #include <cinttypes> #include <bit> int main( void ) { float a = 123.25f; printf( "float %12g 占据 %zu 字节,它在内存中的数据是 0x%02hhX 0x%02hhX 0x%02hhX 0x%02hhX\n" , a , sizeof(a) , ((unsigned char*)(&a))[0] , ((unsigned char*)(&a))[1] , ((unsigned char*)(&a))[2] , ((unsigned char*)(&a))[3] ); int32_t b = 1123450880; printf( "int32_t %12" PRId32 " 占据 %zu 字节,它在内存中的数据是 0x%02hhX 0x%02hhX 0x%02hhX 0x%02hhX\n" , b , sizeof(b) , ((unsigned char*)(&b))[0] , ((unsigned char*)(&b))[1] , ((unsigned char*)(&b))[2] , ((unsigned char*)(&b))[3] ); int32_t c = (int32_t)a; printf( "将 float %g 转化成 int32_t 类型后,值为 %" PRId32 "\n", a, c ); int32_t d = *(int32_t*)&a; printf( "将 float %g 所占内存当成 int32_t 类型格式,则值为 %" PRId32 " ------ 需要注意的是,这是未定义行为\n", a, d ); int32_t e = std::bit_cast<int32_t>( a ); printf( "将 float %g 所占内存当成 int32_t 类型格式,则值为 %" PRId32 " ------ 使用memcpy或std::bit_cast才是良好定义行为\n", a, e ); }