Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Array Decaying ใน C/C++ คืออะไร


Array และ pointer ทำงานคล้ายกัน แต่ sizeof ทำงานต่างกัน เมื่อ array "decay" กลายเป็น pointer (เช่น ส่งไปฟังก์ชัน) จะสูญเสียข้อมูลขนาด

ตัวอย่าง

#include <iostream>
int main() {
    const int a[] = { 2, 3, 5, 7, 11 };
    const int* p = a;  // Array decay to pointer
    std::cout << ( sizeof(p) != sizeof(a) );  // 1 (true)
}

ผลลัพธ์

1

sizeof(a) = ขนาดทั้ง array (5 × sizeof(int))

sizeof(p) = ขนาด pointer (4 หรือ 8 ไบต์)

การสูญเสียข้อมูลขนาดนี้เรียกว่า "Array Decay" เกิดขึ้นเมื่อ array ถูกส่งไปฟังก์ชัน หรือ assign ให้ pointer

แก้ไข: ใช้ std::array หรือ std::vector ที่รักษาขนาดไว้