数组/指针/引用混淆

Array/pointer/reference confusion

本文关键字:指针 数组 引用      更新时间:2023-10-16

可能的重复项:
对指针和参考主题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?)

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

第一个重要的信息是类型为(有界或无界)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] 类型的值,并且不会发生衰减。

困难的部分是考虑到数组不是按值传递,而是衰减为指针。

你的一些声明是语法错误,其他一些不是(但也不是你可能认为的那样)

在您的情况下,唯一有意义的是 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.这不代表任何间接:它只是别名一个整数)