在C++中将数组传递给函数的不同语法
#include <stdio.h>
void test2(int (&some_array)[3]){
// passing a specific sized array by reference? with 3 pointers?
}
void test3(int (*some_array)[3]){
// is this passing an array of pointers?
}
void test1(int (some_array)[3]){
// I guess this is the same as `void test1(some_array){}`, 3 is pointless.
}
int main(){
//
return 0;
}
以上3种语法有什么区别?我在每个部分都添加了评论,以使我的问题更加具体。
回答
void test2(int (&some_array)[3])
这是传递对 3 个数组的引用int,例如:
void test2(int (&some_array)[3]) {
...
}
int arr1[3];
test2(arr1); // OK!
int arr2[4];
test2(arr2); // ERROR!
void test3(int (*some_array)[3])
这是传递一个指向 3 个数组的指针int,例如:
void test3(int (*some_array)[3]) {
...
}
int arr1[3];
test3(&arr1); // OK!
int arr2[4];
test3(&arr2); // ERROR!
void test1(int (some_array)[3])
现在,这就是事情变得有点有趣的地方。
在这种情况下括号是可选的(在引用/指针情况下它们不是可选的),所以这等于
void test1(int some_array[10])
这反过来只是语法糖
void test1(int some_array[])
(是的,数字被忽略)
这反过来只是语法糖
void test1(int *some_array)
因此,不仅数字被忽略,而且它只是一个简单的指针被传入。并且任何固定数组衰减到指向其第一个元素的指针,这意味着任何数组都可以传入,即使声明仅建议允许使用 3 个元素,例如:
void test1(int (some_array)[3]) {
...
}
int arr1[3];
test1(arr1); // OK!
int arr2[10];
test1(arr2); // ALSO OK!
int *arr3 = new int[5];
test1(arr3); // ALSO OK!
delete[] arr3;
现场演示