다중포인터(2중 포인터)
#include <iostream>
int main() {
using namespace std;
int *ptr = nullptr;
int **ptrptr = nullptr;
int value = 5;
ptr = &value;
ptrptr = &ptr;
cout << ptr << " " << *ptr << " " << &ptr << endl;
cout << ptrptr << " " << *ptrptr << " " << &ptrptr << " " << **ptrptr << endl;
return 0;
}
실행결과
00F9FC78 5 00F9FC70
00F9FC70 00F9FC78 00F9FC74 5
ptr : value 의 주소값
*ptr : value 의 값에 접근 (de-referencing)
&ptr : ptr 포인터 변수의 주소값
ptrptr : ptr 포인터 변수의 주소값
*ptrptr : value 의 주소값
&ptrptr : ptrptr 포인터 변수의 주소값
**ptrptr : value 의 값에 접근 (de-referencing)
2중 포인터로 2차원 배열을 만드는 경우를 살펴보자.
#include <iostream>
int main() {
using namespace std;
const int row = 3;
const int col = 5;
int* r1 = new int[col] {1, 2, 3, 4, 5};
int* r2 = new int[col] {6, 7, 8, 9, 10};
int* r3 = new int[col] {11, 12, 13, 14, 15};
int** rows = new int* [row] {r1, r2, r3};
for (int r = 0; r < row; ++r) {
for (int c = 0; c < col; ++c) {
cout << rows[r][c] << " ";
}
cout << endl;
}
return 0;
}
출력결과
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
이 과정은 어떻게 이루어지는 것인가 r1은, int 를 원소로 가지는 { 1, 2, 3, 4, 5 } 의 값을 가진 메모리의 주소가 저장되어 있다. r2, r3 도 마찬가지.
rows 는 *int 를 원소로 가지는(메모리 주소값을 가지는) 배열의 메모리 주소를 갖게된다.
32비트에서 실행한거라 int가 4바이트임
그렇다면 cout << rows[r][c] << " ";
에서 어떻게 바로 value 가 출력되는 것일까?
배열은 포인터이다.
포인터 연산을 생각해보자.
*(ptr + i) 는 ptr[i] 과 동일하다.
배열 첨자인 []은 간접참조 * 과 동일하다.
즉, rows[1][1] 은 *(*(rows + 1) +1)
과 동일한 것임.
위 내용은 미흡한 점이 많을 수 있습니다.