如果传递给函数,则确定数组的大小 [英] determine size of array if passed to function
问题描述
如果传递给另一个函数(未传递大小),是否可以确定数组的大小?数组初始化为 int array[] = { XXX } ..
Is it possible to determine the size of an array if it was passed to another function (size isn't passed)? The array is initialized like int array[] = { XXX } ..
我知道不可能执行 sizeof ,因为它会返回指针的大小.. 我问的原因是因为我需要在传递数组的另一个函数中运行 for 循环.我试过类似的东西:
I understand that it's not possible to do sizeof since it will return the size of the pointer .. Reason I ask is because I need to run a for loop inside the other function where the array is passed. I tried something like:
for( int i = 0; array[i] != NULL; i++) {
........
}
但我注意到在数组的近端,array[i] 有时包含垃圾值,如 758433,这不是数组初始化中指定的值.
But I noticed that at the near end of the array, array[i] sometimes contain garbage values like 758433 which is not a value specified in the initialization of the array..
推荐答案
其他答案忽略了 C++ 的一个特性.您可以通过引用传递数组,并使用模板:
The other answers overlook one feature of c++. You can pass arrays by reference, and use templates:
template <typename T, int N>
void func(T (&a) [N]) {
for (int i = 0; i < N; ++i) a[i] = T(); // reset all elements
}
那么你可以这样做:
int x[10];
func(x);
但请注意,这只适用于数组,不适用于指针.
but note, this only works for arrays, not pointers.
然而,正如其他答案所指出的,使用 std::vector
是更好的选择.
However, as other answers have noted, using std::vector
is a better choice.
这篇关于如果传递给函数,则确定数组的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!