代碼輸出 8 12(或 4 12),主函數中 sizeof(arr) 為 12,傳入函數後 sizeof(arr) 變為 8/4。
void print(int a[]) { // 等價於 int *a
cout << sizeof(a); // 輸出指針大小:64位系統8字節,32位4字節
}
int main() {
int a[3] = {1,2,3}; // int[3] 類型
cout << sizeof(a); // 輸出數組總大小:3 * sizeof(int) = 12
print(a); // 數組退化為 int*,丟失長度信息
}
template
void print(T (&arr)[N]) {
cout << "數組大小: " << N << ", 總字節: " << sizeof(arr);
}
// 調用:print(a); // 自動推導 N=3
#include
void print(const std::array& arr) {
cout << arr.size(); // 3
}
int main() {
std::array a = {1,2,3};
print(a);
}
void print(const std::vector& vec) {
cout << vec.size();
}
struct ArrayWrapper {
int data[3];
size_t size;
};
void print(ArrayWrapper* w) {
cout << w->size;
}
| 場景 | sizeof 結果 | 說明 |
|---|---|---|
函數參數 int a[] | 指針大小 | 退化為 int* |
函數參數 int a[10] | 指針大小 | 大小被忽略,仍退化 |
主函數 int a[3] | 12 | 完整類型 int[3] |
動態分配 new int[3] | 指針大小 | 返回 int* |
std::array<int,3> | 對象大小 | 包含數組,非退化 |
std::span (C++20)、std::array、std::vector 或模板引用void func(int* arr, size_t len)-Warray-bounds、Clang-Tidy modernize-avoid-c-arrays理解數組退化機制,是寫出安全、現代 C++ 代碼的基石。