2016-11-30 76 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

感謝您的幫助。 –