我需要一些幫助理解指針: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]?
其實,你不應該使用這個初始化:類型的' 「12345」 是'字符常量[6]'。爲了避免向後兼容性問題,可以將這種類型衰減爲'char *',但是你放棄了'const'。初始化應該是'char const * buf =「12345」;'。 –