C 中将数组和数组指针传递给函数的区别
C 语言中这两个函数有什么区别?
void f1(double a[]) {
//...
}
void f2(double *a) {
//...
}
如果我要在一个相当长的数组上调用这些函数,这两个函数的行为会有所不同吗?一个会比另一个使用更多的堆栈空间吗?
What is the difference between these two functions in C?
void f1(double a[]) {
//...
}
void f2(double *a) {
//...
}
If I were to call the functions on a substantially long array, would these two functions behave differently? Would one use more stack space than the other?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,一些标准语言:
因此,简而言之,任何声明为
T a[]
或T a[N]
的函数参数都会被视为如同它被声明为T *a
。那么,为什么数组参数被视为被声明为指针呢?原因如下:
给定以下代码:
在对
foo
的调用中,数组表达式arr
不是sizeof
或& 的操作数。
,因此根据6.2.3.1/3,其类型从“int
的10元素数组”隐式转换为“指向int
的指针”。因此,foo
将接收一个指针值,而不是一个数组值。由于 6.7.5.3/7,您可以将
foo
写为但它会被解释为
因此,这两种形式是相同的。
6.7.5.3/7中的最后一句是C99引入的,基本上意味着如果你有一个参数声明,比如
a
对应的实际参数必须是一个数组至少 10 个元素。First, some standardese:
So, in short, any function parameter declared as
T a[]
orT a[N]
is treated as though it were declaredT *a
.So, why are array parameters treated as though they were declared as pointers? Here's why:
Given the following code:
In the call to
foo
, the array expressionarr
isn't an operand of eithersizeof
or&
, so its type is implicitly converted from "10-element array ofint
" to "pointer toint
" according to 6.2.3.1/3. Thus,foo
will receive a pointer value, rather than an array value.Because of 6.7.5.3/7, you can write
foo
asbut it will be interpreted as
Thus, the two forms are identical.
The last sentence in 6.7.5.3/7 was introduced with C99, and basically means that if you have a parameter declaration like
the actual parameter corresponding to
a
must be an array with at least 10 elements.区别纯粹是语法上的。在 C 语言中,当数组表示法用于函数参数时,它会自动转换为指针声明。
The difference is purely syntaxic. In C, when the array notation is used for a function parameter, it is automatically transformed into a pointer declaration.
不,它们之间没有区别。为了测试我在 Dev C++(mingw) 编译器中编写了这段 C 代码:
:
当我在 IDA 中的两个调用版本的二进制文件的 .exe 中反汇编 main 函数时,我得到完全相同的汇编代码,如下所示 此调用的两个版本之间没有区别,至少编译器对它们的威胁相同。
No, there is no difference between them. To test I wrote this C code in Dev C++(mingw) compiler:
When I disassemble main function in .exe of both calling versions of binary file in IDA I get exactly the same assembly code like below:
So there is no difference between the two versions of this call, at least the compiler threats them equally.