假设我正在传递
int arr[10];
作为函数的参数。
所有这些有效的功能原型是什么?它们在论证方面有何不同?为什么?
这是我目前所知的(不确定是否正确)
1. void foo(int &arr); //a reference to an array, which preserve the size attribute?
2. void foo(int &arr[]); //the same (is it)?
3. void foo(int (&arr)[]); //I don't know
4. void foo(int &arr[10]); //is it the same as 2?
5. void foo(int (&arr)[10]);//no idea
6. void foo(int *arr); //a decayed pointer of the array, pointing to the first element of the array, losing the size attribute?
7. void foo(int *arr[]); //the same (is it?)
8. void foo(int (*arr)[]); //a pointer to an array, preserve the size
9. void foo(int *arr[10]); //the same as 7 (is it?)
10. void foo(int (*arr)[10]);//is the same as 8 (is it?)
11. void foo(int arr[]); //is the same as 6 (is it?)
12. void foo(int arr[10]); // is the same as 6 (is it?)
(我知道这需要一个冗长的解释,抱歉,我完全糊涂了......)
答案 0 :(得分:8)
第一个重要信息是,类型为(有界或无界)T
数组的参数将转换为指向T
的指针。即int arr[]
和int arr[10]
都转换为int * arr
。请注意,转换仅在顶级数组上执行,即它不会出现在int (*arr)[10]
中,它是指向int数组的指针。
此外,标识符右侧的内容比左侧的内容绑定得更紧密,即int *arr[10]
是一个数组,而int (*arr)[10]
是一个指针。
最后,引用的数组和指针是无效的,指针和对无界数组的引用也是如此。
1. void foo(int &arr); // can't pass, reference to int
2. void foo(int &arr[]); // invalid, pointer to reference to int
3. void foo(int (&arr)[]); // invalid, reference to unbounded array of int
4. void foo(int &arr[10]); // invalid, pointer to reference to int
5. void foo(int (&arr)[10]); // can pass, reference to an array of int
6. void foo(int *arr); // can pass, pointer to int
7. void foo(int *arr[]); // can't pass, pointer to pointer to int
8. void foo(int (*arr)[]); // invalid, pointer to an unbounded array of int.
9. void foo(int *arr[10]); // can't pass, pointer to pointer to int
10. void foo(int (*arr)[10]); // can't pass, pointer to array of int
11. void foo(int arr[]); // can pass, pointer to int
12. void foo(int arr[10]); // can pass, same as above
使用arr
作为foo
的参数会导致它衰减到指向其第一个元素的指针 - 传递给foo
的值将为int *
类型。请注意,您可以将&arr
传递给数字10,在这种情况下,将传递类型int (*)[10]
的值,并且不会发生衰减。
答案 1 :(得分:0)
困难的部分是考虑数组不通过值传递,而是衰减成指针。
你的一些声明是语法错误,其他一些不是(但也不是你想的那样)
在你的情况下,只有一个有意义的是6,11和12。
2,3,4和8有自解释错误消息。 (如果您不理解它们很可能是因为您阅读了具有错误操作员优先级的声明)
t1.cpp:2:19: error: declaration of 'arr' as array of references
t1.cpp:3:22: error: parameter 'arr' includes reference to array of unknown bound 'int []'
t1.cpp:4:21: error: declaration of 'arr' as array of references
t1.cpp:8:22: error: parameter 'arr' includes pointer to array of unknown bound 'int []'
其他人在某种程度上是多余的(引用数组或-pointer-,它们在函数内部表现相同)或者只是错误,因为根据您的意图声明不同的东西(如7,9,10:它们代表“双重间接“,而普通数组只有一个,而1.表示不代表任何间接:它只是别名单个int)