【问题标题】:How to get the length of a int array(method paramater) inside a method? [duplicate]如何在方法中获取 int 数组(方法参数)的长度? [复制]
【发布时间】:2014-09-09 14:28:19
【问题描述】:

我的代码很简单:

#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[] 的实际长度?

【问题讨论】:

  • 嗨,IIRC 你不能,因为函数参数是一个指针。如果你真的需要这个功能,你可以使用std::arraystd::vector

标签: c++ arrays parameters integer


【解决方案1】:

您可以使用函数模板来做到这一点:

#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

【讨论】:

  • 谢谢。您的模板解决方案非常出色。谢谢。
猜你喜欢
  • 1970-01-01
  • 2012-02-03
  • 1970-01-01
  • 2015-06-21
  • 2020-02-10
  • 1970-01-01
  • 2016-06-06
  • 2013-02-03
  • 1970-01-01
相关资源
最近更新 更多