我需要一些帮助理解指针: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”;'。 –