簡體   English   中英

在取消引用 void 指針后強制轉換為 int 是否正確?

[英]It is correct to cast to int after dereferencing a void pointer?

void* aPtr = NULL;  // we don't yet know what it points to.
...
aPtr = &height;     // it has the address of height, but no type yet.
...
int h = (int)*aPtr; // with casting, we can now go to that address
                    // and fetch an integer value.

學習 C 編程;Jeff Szuhay

'通過鑄造,我們現在可以 go [...]'

問題是——我們真的可以嗎?

取消引用和鑄造 Void Ptr(學習 C 編程,Jeff Szuhay)

'通過鑄造,我們現在可以 go [...]'

問題是——我們真的可以嗎?

是的,但顯示的代碼不執行任何取消引用。 好吧,它嘗試取消引用void*並將結果轉換為int 這不是應該做的。 您必須首先轉換為int*然后取消引用該int*

int h = *(int*)aPtr;    // now dereferenced ok (assuming `height` is an `int`)
//      ^   ^
//      |   |
//      |  proper cast
//      |
// dereferencing the right thing

暫無
暫無

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

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