为什么数组在函数中作为参数传递时大小不同

Why is the size of an array different when it's passed as a parameter in a function

template <typename list_type>
int len(list_type list) {

    std::cout << sizeof(list);

    return (sizeof(list) / sizeof(list[1]));
}


int main() {

    int list[5] = {1, 2 ,3 ,5 ,4};

    std::cout << sizeof(list) << "\n";
    len(list);
}

当我 运行 程序时,我得到:20 然后 4。为什么明明是同一个列表却有不同?

数组退化为指针。

listlen() 中的 int*main 中的 int[5]

mentioned here 一样,有两种可能的修复方法:

  • 使用引用
  • 明确使用对数组类型的引用

如果你使用引用那么它会起作用(指针不会衰减),但你仍然需要计算元素的数量:

#include <iostream>

template <typename list_type>
int len(list_type &list) {
    std::cout << sizeof(list) << '\n';
    return (sizeof(list) / sizeof(list[1]));
}

int main() {
    int list[5] = {1, 2 ,3 ,5 ,4};
    std::cout << sizeof(list) << "\n";
    auto element_count = len(list);
    std::cout << "There are " << element_count << " elements in the list.\n";
}

对于第二个选项,你在编译时得到数组的大小:

#include <iostream>

template <typename list_type, size_t N>
int len(list_type (&list) [N]) {
    std::cout << sizeof(list) << '\n';
    return N;
}

int main() {
    int list[5] = {1, 2 ,3 ,5 ,4};
    std::cout << sizeof(list) << "\n";
    auto element_count = len(list);
    std::cout << "There are " << element_count << " elements in the list.\n";
}