Awesome Hacks!

プログラミング初心者なので地道に勉強していきます。分からない人の立場から整理していきます。

char型のアドレス(文字列のアドレス)を取得する

char型のアドレス(char型の格納した文字列のアドレス)を取得したいときに混乱したので、整理。

#include <iostream>
#include <string>

using namespace std;

int main(){

	cout << "<< num が 12345 の場合 >>" << endl;;
	int num = 12345;
	int *np = &num;
	cout << "np          : " << np << endl;			// numのアドレス
	cout << "*np         : " << *np << endl;		// 実体
	cout << "&np         : " << &np << endl;		// アドレスの格納先アドレス
	cout << "(void*)np   : " << (void*)np << endl;	// numのアドレス

	cout << "\n" << endl;

	cout << "<< str が Hello,world! の場合 >>" << endl;;
	char *str = "Hello,world!";
	cout << "str         : " << str << endl;		// ポインタとは別に文字列という意味を持つためアドレスが表示されない
									// よく言えば、C++の機能で自動的に、アドレスでなく文字列全体を表示してくれる
	cout << "*str        : " << *str << endl;		// 実体(文字列の先頭が実体であるため)
	cout << "&str        : " << &str << endl;		// アドレスの格納先アドレス
	cout << "(void*)str  : " << (void*)str << endl;	// 文字列strのアドレス。
										// 文字列として扱ってほしくない(文字列出力してほしくない)のでキャスト

	return 0;	
}


【実行結果】

$ testChar
<< num が 12345 の場合 >>
np          : 0x7fff5055f9e8       // ポインタの中身なのでアドレス
*np         : 12345
&np         : 0x7fff5055f9e0
(void*)np   : 0x7fff5055f9e8    // npと同じなのでアドレス


<< str が Hello,world! の場合 >>
str         : Hello,world!            // アドレスのはずだがうまく取得できない
*str        : H
&str        : 0x7fff5055f9d8      // これはアドレスのアドレス!!!
(void*)str  : 0x10f6a1ef9         // numと合わせて考えて、これがアドレス
$



C/C++ では char* は単純なポインタという意味とは別に、文字列という意味がある。
C++ の cout などの出力機能は、char* は文字列を表現するための型として扱う。
そのため、char型のポインタ(char*) を渡すと文字列として取り扱おうとする。

文字列として扱われないように別の型にキャストしなければならない。
(もしくは書式指定をする。)