2013-06-04 62 views
3

在Visual Studio 2012年,我與指針瞎搞,我意識到,這個計劃一直崩潰:C++設置字符指針爲空

#include  <iostream> 
    using std::cout; 
    using std::endl; 

    int main() 
    { 

     const char* pointer = nullptr; 

     cout << "This is the value of pointer " << pointer << "." << endl; 

     return 0; 

    } 

我的意圖是在設置pointernull,然後打印地址。即使程序編譯,它在運行時崩潰。有人可以解釋發生了什麼嗎?

而且,什麼是在pointer*pointer

+0

@jogojapan並且在那裏有很多問題的副本。 –

+0

@MarkGarcia是...? – jogojapan

回答

7

您正在使用的,在std::coutoperator <<使用時,被解釋爲一個字符串const char*的差異。

它轉換爲void*看到指針的值(地址包含):

cout << "This the value of pointer " << (void*)pointer << "." << endl; 

或者,如果你想成爲迂腐:

cout << "This the value of pointer " << static_cast<void*>(pointer) << "." << endl; 

LIVE EXAMPLE

+0

真棒,非常感謝你! 有沒有辦法打印出內存位置而不必使用類型轉換指針? – Bbvarghe

+0

'static_cast (指針)'會更優雅。 –

+0

@TadeuszKopec和迂腐。 :) –

1

雖然可以如已經建議的那樣做cout << "Pointer is " << (void*)pointer << ".\n";我覺得在這種情況下,這樣做的「C方式」更漂亮(不投射),更易讀:printf("Pointer is %p\n",pointer);

+1

形式上,這也需要一個強制轉換,因爲'%p'轉換需要一個'void *'。在C中,'char *'和'void *'需要具有相同的表示形式,並且我幾乎可以肯定C++中也是如此,因此儘管存在形式上的不正確性,但沒有明智的實現可以在得到用於'%p'轉換的'char *'[用於「明智」的值不包括故意懲罰拋棄演員的人)。它可以「誠實地」中斷指向除字符類型之外的其他類型的指針,因爲它們不需要具有相同的表示。 –