Channi Studies

[C++] 데이터의 주소에 접근하는 방법 본문

C++/포인터 (Pointers)

[C++] 데이터의 주소에 접근하는 방법

Chan Lee 2023. 12. 19. 18:19

C++에서는 & 기호를 통해 데이터의 주소에 접근할 수 있습니다.

값은 16진수 숫자로 반환됩니다.

 

예시를 보여드리겠습니다.

#include <iostream>

using namespace std;

int main() {
  int num{10};

  cout << "Value of num is: " << num << endl;
  cout << "sizeof num is: " << sizeof(num) << endl;
  cout << "Address of num is: " << &num << endl;

  return 0;
}

출력 결과

 

 

비슷한 예시를 포인터에 적용하면 다음과 같습니다.

#include <iostream>

using namespace std;

int main() {
  int *p;

  cout << "Value of num is: " << p << endl;
  cout << "Address of num is: " << &p << endl;
  cout << "sizeof num is: " << sizeof(p) << endl;

  p = nullptr;
  cout << "Value of num is: " << p << endl;

  return 0;
}

실행 결과

포인터 p를 선언할 때, 초기화를 하지 않았기 때문에 초기에는 garbage data가 들어있어서

이상한 value가 들어 있었습니다.

이후 p = nullptr; 를 통해서 값을 0으로 변경하였습니다.

 

중요한 것은 sizeof(pointer) 의 상황입니다.

아시다시피 포인터는 다른 변수 혹은 함수의 위치값을 저장하고 있는 변수입니다.

즉, sizeof(pointer)의 값은 포인터가 가르키는 주소에 있는 변수 타입과는 무관합니다.

다시 말하자면, 각 포인터가 가르키는 값의 타입과 포인터의 용량은 무관합니다.

모든 포인터에게 sizeof 함수를 적용한 값은 전부 동일하게 나타납니다.

 

#include <iostream>

int main() {
  int *p1{nullptr};
  double *p2{nullptr};
  unsigned long long *p3{nullptr};
  vector<string> *p4{nullptr};
  string *p5{nullptr};

  cout << "\nsizeof p1 is: " << sizeof p1 << endl;
  cout << "sizeof p2 is: " << sizeof p2 << endl;
  cout << "sizeof p3 is: " << sizeof p3 << endl;
  cout << "sizeof p4 is: " << sizeof p4 << endl;
  cout << "sizeof p5 is: " << sizeof p5 << endl;
  
  return 0;
}

 

 

하지만 우리는 포인터를 선언할 때 타입도 선언했습니다.

그렇기 때문에 int 타입 포인터에 double 타입 값에 대한 주소를 저장할 수 없습니다.

포인터는 선언된 타입과 다른 타입의 값에 대한 주소를 저장할 수 없습니다.

 

#include <iostream>

int main() {
  int score{10};
  double high_temp{100.7};

  int *score_ptr{nullptr};

  score_ptr = &score;
  cout << "Value of score is: " << score << endl;
  cout << "Address of score is: " << &score << endl;
  cout << "Value of score_ptr is: " << score_ptr << endl;

  // score_ptr = &high_temp;     // Compiler error

  cout << endl;
  return 0;
}