본문 바로가기
코딩/C++

다중 포인터와 동적 다차원 배열

by sonysame 2024. 3. 10.
#include <iostream>

using namespace std;


int main()
{
	int* ptr = nullptr;
	int** ptrptr = nullptr;

	int value = 5;
	ptr = &value;
	ptrptr = &ptr;

	cout << value << " " << *ptr << " " << **ptrptr << endl;
	cout << &value << " " << ptr << " " << *ptrptr << endl;

	//////////////////////////////////////////////////////////////////
    
	const int row = 3;
	const int col = 5;

	const int s2da[row][col] =
	{
		{1,2,3,4,5},
		{6,7,8,9,10},
		{11,12,13,14,15}
	};

	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;
	}
	delete[] r1;
	delete[] r2;
	delete[] r3;
	delete[] rows;

	//////////////////////////////////////////////////////////
	
	int** matrix = new int* [row];
	for (int r = 0; r < row; r++)
		matrix[r] = new int[col];

	for (int r = 0; r < row; ++r) {
		for (int c = 0; c < col; ++c)
			matrix[r][c] = s2da[r][c];
		cout << endl;
	}
	for (int r = 0; r < row; ++r) {
		for (int c = 0; c < col; ++c)
			cout << matrix[r][c] << " ";
		cout << endl;
	}

	for (int r = 0; r < row; r++)
		delete[] matrix[r];
	delete[] matrix;

	int* matrix = new int[row * col];
	
	return 0;
}

'코딩 > C++' 카테고리의 다른 글

std::array  (0) 2024.03.11
std::vector  (0) 2024.03.11
void 포인터  (0) 2024.03.10
for-each 반복문  (0) 2024.03.10
참조 변수 Reference Variable  (0) 2024.03.09