2016-11-30 7 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++では、stringchar *を意味するのではなく、std::stringを意味します。 このインクルード行はコードでは不要です。

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

ありがとうございます。 –