C 中的两个函数有什么区别?
void f1(double a[]) {
//...
}
void f2(double *a) {
//...
}
如果我要在一个相当长的数组上调用这些函数,这两个函数的行为是否会有所不同,它们会在堆栈上占用更多空间吗?
首先,一些标准语:
6.7.5.3 Function declarators (including prototypes)
...
7 A declaration of a parameter as ‘‘array of type’’ shall be adjusted to ‘‘qualified pointer to
type’’, where the type qualifiers (if any) are those specified within the [
and ]
of the
array type derivation. If the keyword static
also appears within the [
and ]
of the
array type derivation, then for each call to the function, the value of the corresponding
actual argument shall provide access to the first element of an array with at least as many
elements as specified by the size expression.
因此,简而言之,任何声明为的函数参数T a[]
or T a[N]
被治疗好像它被宣布了T *a
.
那么,为什么数组参数被视为被声明为指针呢?原因如下:
6.3.2.1 Lvalues, arrays, and function designators
...
3 Except when it is the operand of the sizeof
operator or the unary &
operator, or is a
string literal used to initialize an array, an expression that has type ‘‘array of type’’ is
converted to an expression with type ‘‘pointer to type’’ that points to the initial element of
the array object and is not an lvalue. If the array object has register storage class, the
behavior is undefined.
给出以下代码:
int main(void)
{
int arr[10];
foo(arr);
...
}
在通话中foo
, 数组表达式arr
不是其中任何一个的操作数sizeof
or &
,因此它的类型是从“ 10 元素数组int
“到”指针int
“根据 6.2.3.1/3。因此,foo
将接收一个指针值,而不是一个数组值。
因为6.7.5.3/7,你可以写foo
as
void foo(int a[]) // or int a[10]
{
...
}
但它会被解释为
void foo(int *a)
{
...
}
因此,这两种形式是相同的。
6.7.5.3/7 中的最后一句是在 C99 中引入的,基本上意味着如果你有一个像这样的参数声明
void foo(int a[static 10])
{
...
}
实际参数对应a
必须是一个数组at least10 个元素。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)