本文介绍了用C数组的元素数量++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
比方说,我有一个数组改编
。当以下不给数组元素的数目:的sizeof(ARR)/ sizeof的(ARR [0])
我只能1箱子件事:数组包含不同派生类型的数组类型的元素
我的权利,并在那里(我几乎可以肯定存在的必须的定)等这样的情况?
对不起,琐碎的问题,我是一个Java开发我比较新的C ++。
谢谢!
解决方案
One thing I've often seen new programmers doing this:
void f(Sample *arr)
{
int count = sizeof(arr)/sizeof(arr[0]); //what would be count? 10?
}
Sample arr[10];
f(arr);
So new programmers think the value of count
will be 10. But that's wrong.
Even this is wrong:
void g(Sample arr[]) //even more deceptive form!
{
int count = sizeof(arr)/sizeof(arr[0]); //count would not be 10
}
It's all because once you pass an array to any of these functions, it becomes pointer type, and so sizeof(arr)
would give the size of pointer, not array!
EDIT:
The following is an elegant way you can pass an array to a function, without letting it to decay into pointer type:
template<size_t N>
void h(Sample (&arr)[N])
{
size_t count = N; //N is 10, so would be count!
//you can even do this now:
//size_t count = sizeof(arr)/sizeof(arr[0]); it'll return 10!
}
Sample arr[10];
h(arr); //pass : same as before!
这篇关于用C数组的元素数量++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!