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