2014-10-26 96 views
4

我在理解指針時遇到了一些麻煩。在下面的代碼,我想打印一個變量的地址在2種方式,一旦使用地址運算符,然後使用指針:在C++中使用指針的變量值和地址

#include<iostream> 
using namespace std; 
int main (void) 
{ 
    int x = 10; 
    int *int_pointer; 
    int_pointer = &x; 
    cout << "x address=" << &x << endl; 
    cout << "x address w pointer=" << int_pointer << endl; 
    return 0; 
} 
x address = 0028FCC4 
x address w pointer = 0028FCC4 

可正常工作。但是,當我做同樣的事情,但現在使用字符類型的變量,我得到一些垃圾輸出:

#include<iostream> 
using namespace std; 
int main(void) 
{ 
    char c = 'Q'; 
    char *char_pointer; 
    char_pointer = &c; 
    cout << "address using address operator=" << &c << endl; 
    cout << "address pointed by pointer=" << char_pointer << endl; 
    return 0; 
} 
address using address operator=Q╠╠╠╠£åbªp é 
address pointed by pointer=Q╠╠╠╠£åbªp é 

我不知道爲什麼會這樣。提前致謝。

回答

7

C++庫爲某些類型重載運算符< <。 (char *)就是其中之一。 Cout試圖打印一個字符串,一個由空字符結尾的字符數組。

只投的指針:

cout << "address pointed by pointer" << (void*)char_pointer << endl; 

cout << "address pointed by pointer" << static_cast<void*>(char_pointer) << endl; 
+0

這是正確的,但我補充說明一下。 C++庫爲某些類型重載<<運算符。 (char *)就是其中之一。 C/C++的一個壞處是它們將指針/數組和數組或char/string作爲同義詞處理。 <<操作符(char *)版本是您試圖打印字符串的東西,而不是指針值。當你打印指針時,最好的方法是將它們轉換爲void:reinterpret_cast (point)。 – user3344003 2014-10-27 00:43:59

+0

@ user3344003如果您有更正或改進它的合理建議,請隨時編輯我的答案,或者添加答案,而不是使用評論。 – 2501 2014-10-27 00:45:51

+0

會做。當這是正確的時候,我不想添加另一個答案。 – user3344003 2014-10-27 00:47:11

0

它打印出一些假的東西的原因是因爲你的字符沒有一個空終止,這意味着該計劃將繼續尋找一個直到,並在這個過程中將打印出它找到的任何東西。您看到的文本是ASCII,但是由ostream錯誤解釋的地址引用。要獲取內存中的地址,可以使用隱式轉換或static_cast。我更喜歡後者:

cout << "address pointed by pointer=" << static_Cast<void*>(char_pointer) << endl; 
1

像2501說,在不同的措詞,&c,因爲c是char,等於char *,所以它要嘗試打印,直到換行字符'\0'是或隱明確地將字符數組放到std::cout,以便流知道字符數組的末尾在哪裏。

所以,是使用(void *)就像2501所說。