問題描述
常量 0 在 C 和 C++ 中用作空指針.但正如問題指向特定固定地址的指針" 似乎可以使用分配固定地址.在任何系統中,對于訪問地址 0 的任何低級任務,是否有任何可想象的需求?
The constant 0 is used as the null pointer in C and C++. But as in the question "Pointer to a specific fixed address" there seems to be some possible use of assigning fixed addresses. Is there ever any conceivable need, in any system, for whatever low level task, for accessing the address 0?
如果有,如何用 0 為空指針和所有來解決?
If there is, how is that solved with 0 being the null pointer and all?
如果不是,那么是什么確定沒有這種需要?
If not, what makes it certain that there is not such a need?
推薦答案
無論是在 C 中還是在 C++ 中,空指針值都與物理地址 0
沒有任何關聯.您在源代碼中使用常量0
來設置指向空指針值的指針,這只不過是一個語法糖.編譯器需要將其轉換為特定平臺上用作空指針值的實際物理地址.
Neither in C nor in C++ null-pointer value is in any way tied to physical address 0
. The fact that you use constant 0
in the source code to set a pointer to null-pointer value is nothing more than just a piece of syntactic sugar. The compiler is required to translate it into the actual physical address used as null-pointer value on the specific platform.
換句話說,源代碼中的 0
沒有任何物理重要性.例如,它可能是 42
或 13
.IE.語言作者,如果他們愿意的話,可以這樣做,這樣你就必須執行 p = 42
以便將指針 p
設置為空指針值.同樣,這并不意味著必須為空指針保留物理地址 42
.編譯器需要將源代碼 p = 42
翻譯成機器代碼,這些機器代碼將填充實際的物理空指針值(0x0000
或 0xBAAD
) 進入指針 p
.這正是使用常量 0
時的情況.
In other words, 0
in the source code has no physical importance whatsoever. It could have been 42
or 13
, for example. I.e. the language authors, if they so pleased, could have made it so that you'd have to do p = 42
in order to set the pointer p
to null-pointer value. Again, this does not mean that the physical address 42
would have to be reserved for null pointers. The compiler would be required to translate source code p = 42
into machine code that would stuff the actual physical null-pointer value (0x0000
or 0xBAAD
) into the pointer p
. That's exactly how it is now with constant 0
.
另請注意,C 和 C++ 都沒有提供嚴格定義的功能,允許您將特定的物理地址分配給指針.因此,您關于如何將 0 地址分配給指針"的問題正式沒有答案.您根本無法為 C/C++ 中的指針分配特定地址.但是,在實現定義的功能領域,顯式整數到指針的轉換旨在產生這種效果.所以,你會這樣做
Also note, that neither C nor C++ provides a strictly defined feature that would allow you to assign a specific physical address to a pointer. So your question about "how one would assign 0 address to a pointer" formally has no answer. You simply can't assign a specific address to a pointer in C/C++. However, in the realm of implementation-defined features, the explicit integer-to-pointer conversion is intended to have that effect. So, you'd do it as follows
uintptr_t address = 0;
void *p = (void *) address;
注意,這和做不一樣
void *p = 0;
后者總是產生空指針值,而前者在一般情況下不會.前者通常會產生一個指向物理地址 0
的指針,它可能是也可能不是給定平臺上的空指針值.
The latter always produces the null-pointer value, while the former in general case does not. The former will normally produce a pointer to physical address 0
, which might or might not be the null-pointer value on the given platform.
這篇關于我可以想訪問地址零嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!