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
팁: 포인터 변수를 선언하는 세 가지 방법이 있지만 첫 번째 방법이 선호됩니다.
string* mystring; // Preferred
string *mystring;
string * mystring;