C ++ポインタ


ポインタの作成

前の章から、演算子を使用して変数のメモリアドレスを取得できることを学びました。&

string food = "Pizza"; // A food variable of type string

cout << food;  // Outputs the value of food (Pizza)
cout << &food; // Outputs the memory address of food (0x6dfed4)

ただし、ポインタは、メモリアドレスを値として格納する変数です

intポインタ変数は、同じ型のデータ型(またはなど)を指しstring、演算子を使用して作成され*ます。使用している変数のアドレスがポインターに割り当てられます。

string food = "Pizza";  // A food variable of type string
string* ptr = &food;    // A pointer variable, with the name ptr, that stores the address of food

// Output the value of food (Pizza)
cout << food << "\n";

// Output the memory address of food (0x6dfed4)
cout << &food << "\n";

// Output the memory address of food with the pointer (0x6dfed4)
cout << ptr << "\n";

例の説明

アスタリスク記号 ( )を使用して、変数ptr指す名前のポインター変数を作成しますポインターのタイプは、操作している変数のタイプと一致する必要があることに注意してください。string*string* ptr

演算子を使用して、と&呼ばれる変数のメモリアドレスを格納し、foodそれをポインタに割り当てます。

ここで、のメモリアドレスのptr値を保持します。food

ヒント:ポインター変数を宣言する方法は3つありますが、最初の方法をお勧めします。

string* mystring; // Preferred
string *mystring;
string * mystring;

C ++演習

エクササイズで自分をテストする

エクササイズ:

の名前でポインタ変数を作成します。これは、 という名前の変数ptrを指す必要があります。stringfood

string food = "Pizza";
  = &;