簡體   English   中英

指向浮點指針的 int 指針 - reinterpret_cast

[英]int pointer to float pointer - reinterpret_cast

以下是代碼:

int a = 1;
int* ptr = &a;
float* p1 = (float*)ptr // or reinterpret_cast<float*>(ptr);
cout << *p1 << endl;

當我嘗試打印浮點指針 p1 指向的值時,我得到的答案是:1.4013e-45。 誰能解釋為什么會這樣?

誰能解釋為什么會這樣?

您通過與指向的 object 的類型不兼容的指針訪問 object,因此程序的行為未定義。

我希望得到“1”作為 output。

要獲得浮點數 1,您可以將 static_cast int 轉換為浮點數,或者簡單地讓轉換為隱式:

float f = a;
std::cout << f;

在浮點或雙精度表示中使用的 Integer 值是非正規的,並根據IEEE 754 標准進行轉換。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM