如何在方法中获取int数组(方法参数)的长度?

时间:2014-09-09 14:28:20

标签: c++ arrays parameters integer

我的代码非常简单:

#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

这意味着当一个[]被转换为函数test()的参数时,已经作为int *恶化,所以size(b)的输出是4,而不是12.所以,我的问题是,如何在函数test()中获得b []的实际长度?

1 个答案:

答案 0 :(得分:6)

您可以使用功能模板执行此操作:

#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