C++のアドレスから文字列を取得する方法がわかりません。住所から文字列を受け取る方法は?
が、これはアドレスですふり:0x00020348 このアドレスは「おいしい」の値を保持しているふり
どのように私は、アドレス0x00020348から「おいしい」の文字列を取得するのでしょうか? ありがとうございます。
C++のアドレスから文字列を取得する方法がわかりません。住所から文字列を受け取る方法は?
が、これはアドレスですふり:0x00020348 このアドレスは「おいしい」の値を保持しているふり
どのように私は、アドレス0x00020348から「おいしい」の文字列を取得するのでしょうか? ありがとうございます。
この回答は、コメントのダイアログを拡大するのに役立ちます。
例として、次のコードを参照してください。
#include <stdio.h>
#include <string.h>
#include <string>
int main()
{
// Part 1 - Place some C-string in memory.
const char* const pszSomeString = "delicious";
printf("SomeString = '%s' [%08p]\n", pszSomeString, pszSomeString);
// Part 2 - Suppose we need this in an int representation...
const int iIntVersionOfAddress = reinterpret_cast<int>(pszSomeString);
printf("IntVersionOfAddress = %d [%08X]\n", iIntVersionOfAddress, static_cast<unsigned int>(iIntVersionOfAddress));
// Part 3 - Now bring it back as a C-string.
const char* const pszSomeStringAgain = reinterpret_cast<const char* const>(iIntVersionOfAddress);
printf("SomeString again = '%s' [%08p]\n", pszSomeStringAgain, pszSomeStringAgain);
// Part 4 - Represent the string as an std::string.
const std::string strSomeString(pszSomeStringAgain, strlen(pszSomeStringAgain));
printf("SomeString as an std::string = '%s' [%08p]\n", strSomeString.c_str(), strSomeString.c_str());
return 0;
}
パート1 - 変数pszSomeString
はあなたのために(任意の値が、0x00020348
を模索しようとしているメモリ内の実際の文字列を表している必要があります例)。
パート2 - あなたがint
としてポインタ値を格納したので、iIntVersionOfAddress
は、ポインタの整数表現であることを述べました。
パート3 - 次に、整数「ポインタ」を取り出してconst char* const
に復元し、再びC文字列として扱うことができます。
パート4 - 最後に、C文字列ポインタと文字列の長さを使用してstd::string
を作成します。 C文字列がヌル文字('\0'
)で終わっているので実際には文字列の長さは必要ありませんが、論理的に長さを計算する必要がある場合はstd::string
コンストラクタのこの形式を示しています。
SomeString = 'delicious' [0114C144]
IntVersionOfAddress = 18137412 [0114C144]
SomeString again = 'delicious' [0114C144]
SomeString as an std::string = 'delicious' [0073FC64]
ポインタアドレスが変化するが、予想されるように、第1の3進ポインタ値は、同じで次のよう
出力されます。 std::string
バージョン用に構築された新しい文字列バッファは、まったく異なるアドレスであり、予想通りです。
最終的なメモ - あなたのコードについては何も知らずに、は通常、int
よりも汎用ポインタの方が優れていると考えられます。