c++ - 数组/指针/引用混淆

标签 c++ arrays pointers reference prototype

<分区>

Possible Duplicate:
Confusion over C++ pointer and reference topic

假设我路过

int arr[10];

作为函数的参数。

这些都是有效的函数原型(prototype)吗?它们在论点方面有何不同?为什么?

这是我目前知道的(不确定是否正确)

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 的指针。 IE。 int arr[]int arr[10] 都被转换为 int * arr。请注意,转换仅在顶级数组上执行,即它不会发生在 int (*arr)[10] 中,它是指向 int 数组的指针。

此外,标识符右边的东西比左边的东西绑定(bind)得更紧密,即 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] 类型的值,并且不会发生衰减。

关于c++ - 数组/指针/引用混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12939739/

相关文章:

c++ - 如何在数组中找到两个缺失值?

c - 关于函数返回的 char 指针的最佳实践

c++ - 将自定义字符串放入文件中

c++ - _malloca 和 malloc 有什么区别?

java - 查找数组中最大元素的索引

c++ - 删除后内存泄漏 []

c++ - 如何区分构造函数

C++ 堆栈溢出异常,可能是由于递归

c++ - C++ 中的引用变量存储什么值?

ios - 将两个不同类型的数组排序为一个