在这里,我们将看到什么是数组衰减。数组类型和尺寸的损失称为数组衰减。当我们通过指针或值将数组传递给函数时,就会发生这种情况。第一个地址被发送到作为指针的数组。这就是为什么数组的大小不是原始大小。
让我们来看一个使用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