C++

C++ 새로운 연산자를 사용해 2D 배열을 동적 선언하는 방법

김구티2 2024. 5. 28. 07:41

C++에서 다차원 배열은 배열의 배열로서 간단한 단어로 표현된다. 다차원 배열의 데이터는 표 형식으로 저장된다. 아래는 N차원 배열을 선언하는 일반적인 형태다.

 

구문:

data_type array_name[size1][size2]….[sizeN];
data_type: Type of data to be stored in the array. 
Here data_type is valid C/C++ data type
array_name: Name of the array
size1, size2, …, sizeN: Sizes of the dimensions

 

즉, 2차원 배열은 단일 차원 배열의 배열이라 할 수 있다.

 

2D 배열의 구문:

data_type array_name[x][y];
data_type: Type of data to be stored. Valid C/C++ data type.

 

아래 그림은 2D 배열을 도식적으로 표현한 것이다.

여기서 2D 배열이 주어지면, C++에서 새로운 것을 사용하여 2D 배열에 대한 메모리를 동적으로 할당하는 것이 우리의 과제다. 그리고 다음과 같은 값을 갖는 3개의 행과 4개의 열로 2D 배열을 선언하는 것이 해답이 될 수 있을 것이다.

 

1 2 3 4
5 6 7 8
9 10 11 12

 

① 단일 포인터 사용하는 방법: 이 방법에서는 M*N 크기의 메모리 블록을 할당한 다음, 포인터 산술을 사용하여 메모리 블록에 액세스한다.

 

예시:

// C++ program to dynamically allocate
// the memory for 2D array in C++
// using new operator
#include <iostream>
using namespace std;

// Driver Code
int main()
{
     // Dimensions of the 2D array
     int m = 3, n = 4, c = 0;

     // Declare a memory block of
     // size m*n
     int* arr = new int[m * n];

     // Traverse the 2D array
     for (int i = 0; i < m; i++) {
          for (int j = 0; j < n; j++) {

               // Assign values to
               // the memory block
               *(arr + i * n + j) = ++c;
          }
     }

     // Traverse the 2D array
     for (int i = 0; i < m; i++) {
          for (int j = 0; j < n; j++) {

               // Print values of the
               // memory block
               cout << *(arr + i * n + j)
                       << " ";
          }
          cout << endl;
     }

          //Delete the array created
          delete[] arr;

     return 0;
}

 

출력:

1 2 3 4 
5 6 7 8 
9 10 11 12

 

② 포인터 배열를 사용하는 방법: 여기서는 포인터 배열이 생성된 다음 각 메모리 블록으로 이동한다. 아래는 개념을 설명하기 위한 다이어그램이다.

 

다음은 동일한 프로그램 예시다:

// C++ program to dynamically allocate
// the memory for 2D array in C++
// using new operator
#include <iostream>
using namespace std;

// Driver Code
int main()
{
     // Dimensions of the array
     int m = 3, n = 4, c = 0;

     // Declare memory block of size M
     int** a = new int*[m];

     for (int i = 0; i < m; i++) {

          // Declare a memory block
          // of size n
          a[i] = new int[n];
     }

     // Traverse the 2D array
     for (int i = 0; i < m; i++) {
          for (int j = 0; j < n; j++) {

               // Assign values to the
               // memory blocks created
               a[i][j] = ++c;
          }
     }

     // Traverse the 2D array
     for (int i = 0; i < m; i++) {
          for (int j = 0; j < n; j++) {

               // Print the values of
               // memory blocks created
               cout << a[i][j] << " ";
          }
          cout << endl;
     }

     // Delete the array created
     for (int i = 0; i < m; i++) // To delete the inner
                                           // arrays
          delete[] a[i];
     delete[] a; // To delete the outer array
                      // which contained the pointers
                      // of all the inner arrays

     return 0;
}

 

출력:

1 2 3 4 
5 6 7 8 
9 10 11 12

 

728x90