C ++ char数组指针混乱

时间:2012-09-02 23:47:17

标签: c++ 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

现在混乱:

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]的地址?

3 个答案:

答案 0 :(得分:3)

char指针在某种意义上有些特殊,因为从历史上看它们已被用作C语言中的字符串.C ++主要向后兼容C,因此它支持C字符串。因此,如果您打印char指针而不是打印地址,它会打印字符串中的每个字符,直到它达到NULL char,就像在C中一样。

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

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

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

您的问题是您尝试使用char了解指针。但是,char很特别。特别是char const*不像任何其他指针那样对待,但它被视为C字符串。那就是&buf[2]确实是第三个字符的地址,但是这个地址被认为是一个以空字符结尾的字符序列的开始,打印这个指针不会导致指针被打印而是字符串从这个地址开始。尝试使用int s进行相同操作以避免此次互动。