2013-03-27 40 views
2

我對以下數據有懷疑;爲什麼指向char的指針與其他數據類型的指針相比表現不同

int intvalue = 3; 
int *pointInt = &intvalue; 

char* p = "string"; 
cout << pointInt << std::endl; // this will give memory location of intvalue which is ok. 
cout << p<< std::endl; // why this will give string value rather than memory location of where string is stored? 
+1

由於重載操作的''<<我 – aragaer 2013-03-27 10:15:30

+0

編輯的標題;問題是關於'char *',而不是指向'char *'的指針。 – 2013-03-27 11:15:10

回答

5

因爲有一個overload of std::ostream& operator<<(std::ostream&, const char*),其中假定所述char*null-terminated string的第一個元素,並打印出整個字符串。

您可以通過嘗試後流char*一個空值終止字符串的第一個元素有很多樂趣:

#include <iostream> 
int main() 
{ 
    char c = 'x'; 
    std::cout << &c << std::endl; 
} 
+0

你有一個奇怪的---甚至可能會說*未定義* - 樂趣的概念。 – 2013-03-27 10:36:49

+0

@JimBalter可以花幾個小時運行該代碼並查看出現的漂亮符號...... – juanchopanza 2013-03-27 10:38:37

1

關鍵字操作符重載 - 是iostream實例只是另一種方法std::cout負責不同的字符和句柄。確切的實施也可能會產生的「Hello World」

0
cout << (void *) p << std::endl; 

我希望這是因爲<<運營商有char*參數特定覆蓋,輸出字符串。

3

char*const char*最常用於指向C樣式空終止的字符串。標準I/O庫在傳入其中一種類型的插入或提取時考慮到這一點。這些函數只是基於想要打印出C風格的字符串的常見程度而設計的。

得到的指針值,你可以嘗試強制轉換爲不同的指針類型:

std::cout << static_cast<void*>(p) << std::endl; 
0

這是operator<<()過載作爲第一個參數COUT對象的類型和類型char*const char*作爲第二。

有很多這樣的重載,你也可以寫一些。

而對於這個特定的過載的原因是爲了「打印」 C風格串(炭的空值終止陣列)

相關問題