确定C数组中元素的数量 [英] Determining the quantity of elements in a C array
本文介绍了确定C数组中元素的数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当调用print_array时,int array []参数(计数)的大小不是预期的大小.似乎sizeof 不返回整个数组的大小,即5 * sizeof(int)= 20.
When print_array is called, the size of the int array[] parameter (count) isn't what was expected. It seems sizeof is not returning the size of the entire array which would be 5*sizeof(int) = 20.
namespace Util
{
void print_array(int array[])
{
size_t count = (sizeof array)/(sizeof array[0]);
cout << count;
// int count = sizeof(array)/sizeof(array[0]);
// for (int i = 0; i <= count; i++) cout << array[i];
}
}
int array_test[5]={2,1,5,4,3};
Util::print_array(array_test);
推荐答案
int array[]
在这里变为int* array
,而sizeof(array)
返回相同的内容sizeof(int*)
.您需要通过引用传递数组来避免这种情况.
int array[]
here becomes int* array
, and sizeof(array)
returns the same thing sizeof(int*)
. You need to pass an array by reference to avoid that.
template <size_t N>
void print_array(int (&array)[N]) {
std::cout << N;
}
int array[] = { 2, 1, 5, 4, 3 };
print_array(array);
这篇关于确定C数组中元素的数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文