# sizeof array

在 C++ 中，對於陣列的大小處理，sizeof 在函式中有個**容易踩雷的陷阱**：如果你把陣列當作參數傳入函式，**它會退化成指標**。這會導致 sizeof 傳回的是**指標的大小**，而不是陣列的實際大小。

# Example

```cpp
#include <iostream>

void test1(char (&a)[10]) {
    std::cout << "test1 called with array of size: "
              << sizeof(a) << " bytes" << std::endl;
}

void test2(char a[20]) {
    std::cout << "test2 called with array of size: "
              << sizeof(a) << " bytes" << std::endl;
}

template <size_t N>
void test3(char (&a)[N]) {
    std::cout << "test3 called with array of size: "
              << sizeof(a) << " bytes" << std::endl;
}

int main() {
    char foo[10];
    char bar[20];

    std::cout << "Size of foo: " << sizeof(foo) << " bytes" << std::endl;
    std::cout << "Size of bar: " << sizeof(bar) << " bytes" << std::endl;

    test1(foo);    // ✅ OK，參數是 char (&)[10]，能正確取得大小
    // test1(bar); // ❌ 編譯錯誤：不匹配的參數型別

    test2(foo); // ✅ 編譯 OK，但...
    test2(bar); // ⚠️ 警告：sizeof 傳回的是指標大小

    test3(foo); // ✅ OK，使用 template 保留大小資訊
    test3(bar); // ✅ OK，template 根據實際大小推導
}
```

# Output

```plaintext
Size of foo: 10 bytes
Size of bar: 20 bytes
test1 called with array of size: 10 bytes
test2 called with array of size: 8 bytes
test2 called with array of size: 8 bytes
test3 called with array of size: 10 bytes
test3 called with array of size: 20 bytes
```

## 整理

| 函式 | 參數型別 | 傳入 foo | 傳入 bar | `sizeof` 結果 | 備註 |
| --- | --- | --- | --- | --- | --- |
| `test1` | `char (&a)[10]` | ✔️ | ❌ | 正確（10） | 固定參考型別，僅限 10 元素 |
| `test2` | `char a[20]` | ✔️ | ✔️ | 錯誤（為指標大小） | 陣列退化為 `char*` |
| `test3` | `char (&a)[N]` | ✔️ | ✔️ | 正確 | 使用 template 推導大小 |

* 陣列作為函數參數時會退化為指標，`sizeof` 取得的是**指標大小**
    
* 若要正確取得大小可以使用：
    
    * **參考型別**（如 `char (&a)[10]`）
        
    * **template + reference**（如 `template <size_t N> void f(char (&a)[N])`）
