C++

C++ 배열 붕괴(Array Decay) 총정리

김구티2 2024. 6. 3. 20:52

1. 배열 붕괴의 개념

배열의 종류와 차원의 손실을 배열의 붕괴라고 한다. 이것은 일반적으로 배열을 값이나 포인터로 함수로 전달할 때 발생한다. 즉, 배열의 크기는 원래의 것이 아니라 메모리에서 포인터가 차지하는 것이다.

 

예시:

// C++ code to demonstrate array decay
#include <iostream>
using namespace std;

// Driver function to show Array decay
// Passing array by value
void aDecay(int* p)
{
     // Printing size of pointer
     cout << "Modified size of array is by "
                  " passing by value: ";
     cout << sizeof(p) << endl;
}

int main()
{
     int a[7] = {
          1, 2, 3, 4, 5, 6, 7,
    };

     // Printing original size of array
     cout << "Actual size of array is: ";
     cout << sizeof(a) << endl;

     // Passing a pointer to array
     aDecay(a);

     return 0;
}

 

출력:

Actual size of array is: 28
Modified size of array is by  passing by value: 8

 

위 코드에서 실제 배열은 7개의 int 요소를 가지고 있으므로 28의 크기를 갖는다. 그러나 값과 포인터로 호출하면, 배열은 포인터로 붕괴하고, 1개의 포인터 크기를 8로 프린트한다.

2. 붕괴를 방지하는 방법

붕괴를 처리하는 일반적인 솔루션은 배열의 크기를 매개 변수로 전달하고, 배열 매개 변수의 크기를 사용하지 않는 것이다. 배열의 붕괴를 방지하는 또 다른 방법은 배열을 참조로 함수로 보내는 것이 있다. 이것은 배열이 포인터로 변환되는 것을 방지하므로 붕괴를 방지하는 것이다.

 

예시:

// C++ code to demonstrate prevention of
// decay of array
#include<iostream>
using namespace std;

// A function that prevents Array decay
// by passing array by reference
void fun(int (&p)[7])
{
     // Printing size of array
     cout << "Modified size of array by "
                  "passing by reference: ";
     cout << sizeof(p) << endl;
}

int main()
{
     int a[7] = {1, 2, 3, 4, 5, 6, 7,};

     // Printing original size of array
     cout << "Actual size of array is: ";
     cout << sizeof(a) <<endl;

     // Calling function by reference
     fun(a);

     return 0;
}

 

출력:

Actual size of array is: 28
Modified size of array by passing by reference: 28

 

위 코드에서 배열을 참조로 전달하면 배열의 붕괴 문제가 해결된다. 두 경우 모두 크기는 28이다.

또한, 배열에 비해 하나의 차원이 더 많은 배열에 포인터로 전달하여 배열의 크기를 보존할 수 있다.

 

예시:

// C++ code to demonstrate array decay
#include <iostream>
using namespace std;

// Function to show that array decay happens
// even if we use pointer
void pDecay(int (*p)[7])
{
     // Printing size of array
     cout << "Modified size of array by "
                  "passing by pointer: ";
     cout << sizeof(p) << endl;
}

int main()
{
     int a[7] = { 1, 2, 3, 4, 5, 6, 7 };

     // Printing original size of array
     cout << "Actual size of array is: ";
     cout << sizeof(a) << endl;

     // Passing a pointer to array
     pDecay(&a);

     return 0;
}

 

출력:

Actual size of array is: 28
Modified size of array by passing by pointer: 8

 

그러나 이 경우 함수의 배열을 2차원 배열로 취급하고, 배열에 저장된 값에 액세스하려면 arr[0][1], arr[0][3],... 등과 같이 액세스해야 한다.

728x90