2012-09-02 70 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相同以避免此交互。