🙇‍♀️다중 포인터

오늘 배울 것 : 아래 함수들의 차이점을 확실하게 알자!

void SetNumber(int* a)
{
	*a = 1;
}

void SetNumber(int& a)
{
	a = 1;
}

void SetMessage(const char* a)
{
	a = "Bye";
}

void SetMessage(const char** a)
{
	*a = "Bye";
}

void SetMessage2(const char*& a)
{
	a = "Bye";
}

🪐1차 포인터

int a = 0;
SetNumber(&a);
cout << a << endl;

SetNumber(&a);를 사용했으니 &을 봐서 포인터 함수를 사용했다

int a = 0;
SetNumber(a);
cout << a << endl;

이렇게 사용했다면 &가 없으니 참조형태의 함수를 사용했다

🪐2차 포인터

// .rdata Hello주소[H][e][l][l][o][\0]
// .rdata Bye주소[B][y][e][\0]
// msg[ Hello주소 ] << 8바이트
const char* msg = "Hello";

msg는 주소를 담는 바구니이고 바구니는 8바이트이며 가르키는 형태는 const char이다 그 바구니를 타고가면 .radta에 Hello주소와[H][e][l][l][o][\0]가 담겨져있다

// [매개변수][RET][지역변수(msg( Hello주소 ))]
SetMessage(msg);
//cout << msg << endl; // Hello? Bye?

여기서 SetMessage가 1차 포인터로 만들어진 함수라면 msg는 변하지 않는다 참조 형태인 2차 포인터 함수라면 msg는 바뀐다

// .rdata Hello주소[H][e][l][l][o][\0]
// msg[ Hello주소 ] << 8바이트
// pp[ &msg ] << 8바이트
const char** pp = &msg;
// *pp = "Bye"; 이렇게 직접적으로 바꿀 수 있다!
cout << msg << endl;

// [매개변수][RET][지역변수(msg( Hello주소 ))][매개변수(a(&msg msg의 주소))][RET][지역변수]
SetMessage(&msg);
  • 다중 포인터를 사용해야 하는 이유!
    • 현재 msg라는 변수는 Hello를 담고있는것이 아니라 Hello의 주소를 담고있음
    • msg가 담고있는 Hello주소의 Hello값을 바꾸기 위해서 다중 포인터를 사용!

태그:

카테고리:

업데이트: