【发布时间】:2017-01-15 20:15:55
【问题描述】:
在 C++ Primer 第 5 版,第 3.5 节,第 115 页中,它给出了以下示例:
int *ptrs[10]; // ptrs is an array of ten pointers to int
int &refs[10] = /* ? */; // error: no arrays of references
int (*Parray)[10] = &arr; // Parray points to an array of ten ints
int (&arrRef)[10] = arr; // arrRef refers to an array of ten ints
我理解了几乎所有的例子,除了一个:
int (*Parray)[10] = &arr; // Parray points to an array of ten ints
要指向一个数组,我可以这样做:
int a[10];
int *p = a;
由于名称“a”也是指向数组的指针,因此现在 p 指向的位置与名称“a”所表示的指针所指的位置相同。
我试图编译本书给出的示例,我期待使用:
int (*Parray)[10] = &arr; // Parray points to an array of ten ints
将具有与我给出的示例相同的效果。问题是没有发生,这里是代码:
#include <iostream>
using namespace std;
int main(int argc, char const *argv[]) {
int arr[10] = {1,1,1,1,1,1,1,1,1,1};
int *ptrs[10];
int (*Parray)[10] = &arr;
int (&arrRef)[10] = arr;
cout << *(Parray + 1) << endl;
cout << Parray[1] << endl;
return 0;
}
此代码编译,并给出以下输出:
0x7fff5c4a2ab8
0x7fff5c4a2ab8
有人能解释一下具体是什么吗:
int (*Parray)[10] = &arr; // Parray points to an array of ten ints
是吗?我能用它做什么?
【问题讨论】:
标签: c++ arrays pointers reference