การสูญเสียประเภทและขนาดของอาร์เรย์เรียกว่าการสลายตัวของอาร์เรย์ มันเกิดขึ้นเมื่อเราส่งอาร์เรย์ไปยังฟังก์ชันด้วยตัวชี้หรือค่า ที่อยู่แรกจะถูกส่งไปยังอาร์เรย์ซึ่งเป็นตัวชี้ ด้วยเหตุนี้ขนาดของอาร์เรย์จึงไม่ใช่ขนาดเดิม
นี่คือตัวอย่างการสลายอาร์เรย์ในภาษา 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