2012-09-02 68 views
2

我需要一些幫助理解指針:C++字符數組指針混亂

基本指針:

int i = 3;   
cout << i << endl; //prints 3 
cout << &i << endl; //prints address of i 

int * p = &i; 
cout << p << endl; //prints the address p points to 
cout << &p << endl; //prints the address of p 
cout << *p << endl; //prints the value stored at the address p points to 

現在,這樣的困惑:

char *buf = "12345"; 
cout << &buf[2] << endl; //prints 345 
cout << buf+2 << endl; //prints 345 
cout << *buf << endl;  //prints 1 
cout << *(buf+2) << endl; //prints 3 
cout << buf << endl;  //prints 12345 
cout << &buf << endl;  //prints 001CFA6C 

如何打印buf的地址[3]?

+1

其實,你不應該使用這個初始化:類型的' 「12345」 是'字符常量[6]'。爲了避免向後兼容性問題,可以將這種類型衰減爲'char *',但是你放棄了'const'。初始化應該是'char const * buf =「12345」;'。 –

回答

3

char指針在歷史上曾被用作C中的字符串,在某種意義上有點特殊.C++大多向後兼容C,所以它支持C字符串。因此,如果您打印指針而不是打印地址,則會打印字符串中的每個字符,直到達到空字符,就像在C中一樣。要打印實際地址,請將指針投射到void*。要打印實際地址,請將指針投射到void*

cout << static_cast<void*>(&buf[3]) << endl;

1

iostreams對char指針有一個特殊的重載(把它們當作指向null終止數組的指針並打印整個數組)。由指針轉換爲void指針,其打印爲數值繞過超載:

std::cout << static_cast<void*>(buf + 3) << std::endl; 
1

你的問題是,你嘗試使用char瞭解指針。但是,char是特別的。特別是char const*不像其他指針那樣對待,但它被視爲C字符串。即&buf[2]確實是第三個字符的地址,但該地址被認爲是以空字符結尾的字符序列的開始,並且打印此指針不會導致打印指針,而是從此地址開始的字符串。嘗試與int相同以避免此交互。