2016-11-30 29 views
0

我现在下面的代码输出位于0位置的字母H,但是我想知道是否有办法输出不只是字母H,还有指针位置字母H的字符串C++中指针的输出位置

感谢

#include "stdafx.h" 
#include <iostream> 
#include <string> 

using namespace std; 
int main(){ 
const char* letterPointer = "Harry"; 
cout << letterPointer[0] << endl 
return 0; 
} 
+0

试过'(void *)&letterPointer [0]'? –

+0

或确实只是'letterPointer' – paddy

+0

你的问题的措辞有点不清楚。看起来你可能试图从一个任意指针获取索引。例如,如果你在字符串中有一个指向_somewhere_的指针,并想知道它的位置。 _e.g._'char * p = strchr(letterPointer,'r');' - 在这种情况下,您可以使用指针运算:'int pos = p - letterPointer;' – paddy

回答

1

这是一种常见的技术,从char *转换为void *用于这一目的,方法如下:

cout << static_cast<const void*>(&letterPointer[0]) << endl; 

顺便说一句,在C++中,string并不意味着char *,而是std::string。 所以这包括行在你的代码中是没有必要的。

#include <string> // You'd probably want to remove this line. 
+0

感谢您的帮助。 –