我们什么时候需要数组的大小作为参数传递 [英] when do we need to pass the size of array as a parameter
问题描述
我感到有点困惑传中C / C数组++。我看到一些案件中,签名是这样的。
I am a little bit confused about pass an array in C/C++. I saw some cases in which the signature is like this
void f(int arr[])
一些是这样的。
void f(int arr[], int size)
有谁阐述什么区别以及何时和如何使用它?
Could anybody elaborate what's the difference and when and how to use it?
推荐答案
首先,传递给函数的数组实际上传递一个指向数组的第一个元素,例如,如果你有
First, an array passed to a function actually passes a pointer to the first element of the array, e.g., if you have
int a[] = { 1, 2, 3 };
f(a);
然后, F()
获得&放大器;一个[0]
传递给它。所以,写你的函数原型的时候,下面的是等价的:
Then, f()
gets &a[0]
passed to it. So, when writing your function prototypes, the following are equivalent:
void f(int arr[]);
void f(int *arr);
这意味着该数组的大小丢失,并 f()的
,在一般情况下,不能确定的大小。 (这是我之所以preFER 无效F(INT * ARR)
的形式在无效F(INT ARR [])
)
This means that the size of the array is lost, and f()
, in general, can't determine the size. (This is the reason I prefer void f(int *arr)
form over void f(int arr[])
.)
有两种情况下, F()
并不需要的信息,并在这两个情况下,确定没有额外的参数给它。
There are two cases where f()
doesn't need the information, and in those two cases, it is OK to not have an extra parameter to it.
首先,在改编
一些特殊的,约定的价值,无论是主叫方和 F()
采取意味着结束。例如,我们可以同意,值 0
表示完成。
First, there is some special, agreed value in arr
that both the caller and f()
take to mean "the end". For example, one can agree that a value 0
means "Done".
那么可以写:
int a[] = { 1, 2, 3, 0 }; /* make sure there is a 0 at the end */
int result = f(a);
和定义 F()
是这样的:
int f(int *a)
{
size_t i;
int result = 0;
for (i=0; a[i]; ++i) /* loop until we see a 0 */
result += a[i];
return result;
}
显然,上述方案仅当的两个的主叫方和被叫方同意公约,并按照它。一个例子是在C库的strlen()
功能。它找到一个 0
计算字符串的长度。如果你传递的东西,没有一个 0
结尾,所有的赌注都关闭,而你是在不确定的行为领土。
Obviously, the above scheme works only if both the caller and the callee agree to a convention, and follow it. An example is strlen()
function in the C library. It calculates the length of a string by finding a 0
. If you pass it something that doesn't have a 0
at the end, all bets are off, and you are in the undefined behavior territory.
第二种情况是,当你真的没有一个数组。在这种情况下, F()
(在你的榜样 INT
)需要一个指向对象的指针。所以:
The second case is when you don't really have an array. In this case, f()
takes a pointer to an object (int
in your example). So:
int change_me = 10;
f(&change_me);
printf("%d\n", change_me);
与
void f(int *a)
{
*a = 42;
}
是好的: F()
不是一个阵列上运行反正
is fine: f()
is not operating on an array anyway.
这篇关于我们什么时候需要数组的大小作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!