如何获得int数组(方法paramater)的方法里面的长度是多少? [英] How to get the length of a int array(method paramater) inside a method?
问题描述
我的code是相当简单:
My code is quite simple:
#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");
}
这code的输出是:
12
4
这意味着当一个[]被转移作为参数传递给函数test(),是已恶化为INT *,所以尺寸的输出(b)为4,而不是12.So的,我的问题是,我怎么能得到b的实际长度[]内的功能测试()?
which means that when a[] is transfered as a parameter to function test(),is has been deteriorated as a int *, so the output of size(b) is 4 ,instead of 12.So ,my question is , how can I get the actual length of b[] inside function test() ?
推荐答案
您可以用一个函数模板做到这一点:
You could do this with a function template:
#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测试(INT B〔])
是另一种说法内部测试(INT * B)
,于是就有了测试
函数内没有数组大小信息。此外,你可以使用它知道自己的尺寸标准库容器类型,如 的std ::阵列
。
Note that in C and C++, int test(int b[])
is another way of saying int test(int* b)
, so there is no array size information inside of the test
function. Furthermore, you could use standard library container types which know their size, such as std::array
.
这篇关于如何获得int数组(方法paramater)的方法里面的长度是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!