3

可能重复:
对 C++ 指针和参考主题的混淆

假设我路过

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?)

(我知道这需要一个冗长的解释,对不起,我完全糊涂了......)

4

2 回答 2

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将是 type int *。请注意,您可以传递&arr给数字 10,在这种情况下,int (*)[10]将传递一个类型的值并且不会发生衰减。

于 2012-10-17T17:27:46.980 回答
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 []'

其他的在某种程度上是多余的(对数组或指针的引用,它们在函数内部的行为相同)或者只是错误的,因为声明的东西与你的意图不同(比如 7,9,10:它们代表“双重间接” ,而普通数组只有一个,而 1. 不代表任何间接:它只是给单个 int 取别名)

于 2012-10-17T17:42:39.543 回答