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;