배열의 유형과 차원이 손실되는 것을 배열 붕괴라고 합니다. 포인터나 값으로 함수에 배열을 전달할 때 발생합니다. 첫 번째 주소는 포인터인 배열로 전송됩니다. 그래서 배열의 크기가 원래 배열의 크기가 아닙니다.
다음은 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);
return 0;
} 출력
Actual size of array is : 40 New size of array by passing the value : 8 New size of array by passing the pointer : 8
배열 붕괴 방지
어레이 붕괴를 방지하는 두 가지 방법이 있습니다.
-
배열의 크기를 매개변수로 전달하여 배열 소멸을 방지하고 배열의 매개변수에 sizeof()를 사용하지 마십시오.
-
참조로 함수에 배열을 전달합니다. 배열이 포인터로 변환되는 것을 방지하고 배열 소멸을 방지합니다.
다음은 C++ 언어에서 배열 붕괴를 방지하는 예입니다.
예시
#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);
return 0;
} 출력
Actual size of array is: 40 New size of array by passing reference: 40