如何获取方法内部int数组(方法参数)的长度

How to get the length of a int array(method paramater) inside a method?

本文关键字:方法 参数 数组 int 获取 何获取 内部      更新时间:2023-10-16

我的代码很简单:

#include <iostream>
using namespace std;
int test(int b[]){
    cout<<sizeof(b)<<endl;
    return 1;
}
int main(){
    int a[] ={1,2,3};
    cout<<sizeof(a)<<endl;
    test(a);
    system("pause");
}

该代码的输出为:

12
4

这意味着当a[]作为参数传递到函数test()时,is已经退化为int*,所以size(b)的输出是4,而不是12。所以,我的问题是,我如何才能在函数test[()中获得b[]的实际长度?

您可以使用一个函数模板:

#include <cstddef> // for std::size_t
template<class T, std::size_t N>
constexpr std::size_t size(T (&)[N])
{ 
  return N;
}

然后

#include <iostream>
int main()
{
    int a[] ={1,2,3};
    std::cout << size(a) << std::endl;
}

注意,在C和C++中,int test(int b[])int test(int* b)的另一种说法,因此test函数内部没有数组大小信息。此外,您可以使用知道其大小的标准库容器类型,例如std::array