什么是 C++ 中的数组衰变?


数组类型和维度丢失称为数组衰变。它发生在我们通过指针或值传递数组到某个函数时。第一个地址发送到数组,它是指针。这就是为什么数组的大小不是原来的大小。

这里是一个 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

更新于: 2020-06-24

2K+ 次浏览

开启你的职业

完成课程并获得认证

立即开始
广告
© . All rights reserved.