什麼是 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+ 次瀏覽

開啟你的職業

完成課程並獲得認證

立即開始
廣告