确定数组的大小,如果传递给函数 [英] determine size of array if passed to function

查看:160
本文介绍了确定数组的大小,如果传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能确定数组的大小,如果它被传递到另一个功能(大小不通过)?数组初始化像int数组[] = {} 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,因为它会返回指针的大小..我之所以问是因为我需要为其中数组传递另一个函数内循环运行。我想是这样的:

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++) {
........
}

不过,我注意到,在数组的近端,数组[我]有时含有像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
}

那么你可以这样做:

then you can do this:

int x[10];
func(x);

但请注意,这只是作品的阵列,不是指针。

然而,由于其他答案已经指出的那样,使用的std ::矢量是一个更好的选择。

However, as other answers have noted, using std::vector is a better choice.

这篇关于确定数组的大小,如果传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆