指针参数和数组参数之间有区别吗? [英] Is there a difference between a pointer parameter and an array parameter?
问题描述
void method(double *v)
void method(double v[5])
这两者之间有什么区别吗?
Is there any difference between these two?
第二个是否更具体,例如v
限于长度为5个元素?
Is the second one more specific, as in v
being constrained to 5 elements in length?
推荐答案
当数组声明为参数类型时,会衰减为指针类型.在您的示例中,
Arrays when declared as parameter types, decay to the pointer types. In your example,
void method(double v[5]);
这里5
根本不起作用,无关紧要,您可能会完全忽略,而是这样写:
Here 5
doesn't play any role at all, it is so insignificant that you may omit it altogether, and write this instead:
void method(double v[]);
与上一个声明完全相同.由于它会衰减为指针,因此以上两个与以下内容完全相同:
which is exactly same as the previous declaration. Since it decays into pointer, so the above two are exactly same as:
void method(double *v); //because array decays to pointer, anyway
也就是说,以下所有都是相同功能的声明:
That is, all the following are declarations of the same function:
void method(double v[5]); //ok : declaration
void method(double v[]); //ok : redeclaration of the above
void method(double *v); //ok : redeclaration of the above
全部完全相同.完全没有区别.
ALL are exactly same. No difference at all.
请注意,以下内容不同:
Note that the following is different however:
void f(double (&v)[5]);
它声明了一个函数,该函数可以采用大小为恰好 5
的双精度数组.如果您传递任何其他大小的数组(或传递指针),则会出现编译错误!
It declares a function which can take array of doubles of size exactly 5
. If you pass array of any other size (or if you pass pointers), it will give compilation error!
这篇关于指针参数和数组参数之间有区别吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!