여기서 우리는 Array Decay가 무엇인지 볼 것입니다. 배열의 유형과 차원이 손실되는 것을 배열 감쇠라고 합니다. 포인터나 값으로 함수에 배열을 전달할 때 발생합니다. 첫 번째 주소는 포인터인 배열로 전송됩니다. 그래서 배열의 크기가 원래 배열의 크기가 아닙니다.
C++ 코드를 사용한 배열 붕괴의 한 예를 살펴보겠습니다.
예
#include<iostream>
using namespace std;
void DisplayValue(int *p) {
cout << "New size of array by passing the value : ";
cout << sizeof(p) << endl;
}
void DisplayPointer(int (*p)[10]) {
cout << "New size of array by passing the pointer : ";
cout << sizeof(p) << endl;
}
int main() {
int arr[10] = {1, 2, };
cout << "Actual size of array is : ";
cout << sizeof(arr) <<endl;
DisplayValue(arr);
DisplayPointer(&arr);
} 출력
Actual size of array is : 40 New size of array by passing the value : 8 New size of array by passing the pointer : 8
이제 C++에서 배열 붕괴를 방지하는 방법을 살펴보겠습니다. 어레이 붕괴를 방지하는 두 가지 방법이 있습니다.
- 배열의 크기를 매개변수로 전달하여 배열 붕괴를 방지하고 배열 매개변수에 sizeof()를 사용하지 않습니다.
- 참조로 배열을 함수에 전달합니다. 배열이 포인터로 변환되는 것을 방지하고 배열 붕괴를 방지합니다.
예
#include<iostream>
using namespace std;
void Display(int (&p)[10]) {
cout << "New size of array by passing reference: ";
cout << sizeof(p) << endl;
}
int main() {
int arr[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
cout << "Actual size of array is: ";
cout << sizeof(arr) <<endl;
Display(arr);
} 출력
Actual size of array is: 40 New size of array by passing reference: 40