2

I need some help understanding pointers:

Basic Pointers:

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

Now the confusion:

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

How do I print the address of buf[3]?

4

3 回答 3

3

char指针在某种意义上有点特殊,因为它们在历史上一直被用作 C 中的字符串。C++ 大多向后兼容 C,因此它支持 C 字符串。所以如果你打印一个char指针,而不是打印地址,它会打印字符串中的每个字符,直到它到达一个 NULL 字符,就像在 C 中一样。

要打印实际地址,请将指针转换为void*.

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

于 2012-09-02T23:50:17.430 回答
1

iostream 对 char 指针有一个特殊的重载(将它们视为指向以 null 结尾的数组的指针并打印整个数组)。通过将指针转换为 void 指针来绕过重载,该指针打印为数值:

std::cout << static_cast<void*>(buf + 3) << std::endl;
于 2012-09-02T23:49:44.983 回答
1

您的问题是您尝试使用char. 不过,char很特别。特别char const*是不被视为任何其他指针,但它被视为 C 字符串。这&buf[2]确实是第三个字符的地址,但这个地址被认为是一个以空字符结尾的字符序列的开始,打印这个指针不会导致指针被打印,而是从这个地址开始的字符串。尝试使用ints 来避免这种交互。

于 2012-09-02T23:50:12.823 回答