問題描述
我知道它是一個整數類型,可以在不丟失數據的情況下轉換為/從指針轉換,但我為什么要這樣做呢?與 void*
用于保存指針和 THE_REAL_TYPE*??
用于指針運算相比,整數類型有什么優勢?
I know it is an integer type that can be cast to/from pointer without loss of data, but why would I ever want to do this? What advantage does having an integer type have over void*
for holding the pointer and THE_REAL_TYPE*
for pointer arithmetic?
編輯
標記為已經被問過"的問題不回答這個.問題是使用 intptr_t
作為 void*
的一般替代品是否是一個好主意,并且那里的答案似乎是不要使用 intptr_t",所以我的問題仍然有效:intptr_t
的一個好的用例是什么?
EDIT
The question marked as "already been asked" doesn't answer this. The question there is if using intptr_t
as a general replacement for void*
is a good idea, and the answers there seem to be "don't use intptr_t", so my question is still valid: What would be a good use case for intptr_t
?
推薦答案
主要原因,你不能對 void *
進行按位運算,但你可以對 intptr_t 做同樣的操作
.
The primary reason, you cannot do bitwise operation on a void *
, but you can do the same on a intptr_t
.
在許多需要對地址執行按位運算的場合,可以使用intptr_t
.
On many occassion, where you need to perform bitwise operation on an address, you can use intptr_t
.
然而,對于按位運算,最好的方法是使用 unsigned
對應物,uintptr_t
.
However, for bitwise operations, best approach is to use the unsigned
counterpart, uintptr_t
.
如 其他答案中所述,@chux,指針比較是另一個重要方面.
As mentioned in the other answer by @chux, pointer comparison is another important aspect.
此外,FWIW,根據 C11
標準,§7.20.1.4,
Also, FWIW, as per C11
standard, §7.20.1.4,
這些類型是可選的.
這篇關于intptr_t 有什么用?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!