Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Array Decay (Mảng suy biến) trong C++ là gì?


Array Decay là mất kiểu và kích thước của mảng khi truyền mảng vào hàm bằng con trỏ hoặc giá trị. Địa chỉ đầu tiên được gửi đi (dạng con trỏ), do đó sizeof() trên tham số không trả về kích thước mảng gốc.

Ví dụ

#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;
}

Kết quả

Actual size of array is: 40
New size of array by passing the value: 8
New size of array by passing the pointer: 8

Kích thước thực tế 40 byte (10 int × 4 byte). Khi truyền mảng → con trỏ 8 byte (64-bit). Truyền con trỏ mảng → cũng 8 byte.

Cách ngăn chặn Array Decay

  1. Truyền kích thước mảng làm tham số, không dùng sizeof() trên tham số mảng.
  2. Truyền mảng bằng tham chiếu (reference) - ngăn chặn chuyển đổi thành con trỏ.

Ví dụ truyền tham chiếu

#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;
}

Kết quả

Actual size of array is: 40
New size of array by passing reference: 40

Khi truyền tham chiếu int (&p)[10], sizeof(p) giữ nguyên 40 byte.