[英]Different syntax of passing an array to a function in 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;
在您的代碼中, test3
是傳遞指向數組的指針的正確方法,如果這是您想要的。
void foo(int (*some_array)[3])
{
for (size_t i = 0; i < 3; ++i) {
printf("some_array[%zu]: %d\n", i, (*some_array)[i]);
}
}
int main()
{
int a[3] = { 4, 5, 6 };
foo(&a);
return 0;
}
運行此代碼會返回您期望的結果:
some_array[0]: 4
some_array[1]: 5
some_array[2]: 6
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.