在 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
是?我可以用它做什么?
最佳答案
Could someone explain exactly what:
int (*Parray)[10] = &arr; // Parray points to an array of ten ints
is ? and what I can do with it ?
Parray
的类型是int (*)[10]
,意味着它只能赋值给指向int [10]类型对象的指针]
。
因此,您拥有的是一个指向 10 个元素的数组(通过 &arr
获得)开头的指针。
而通过Parray
访问arr
的元素的方式需要先解引用指针Parray
来获取 arr
你可以索引到:
因此做
(*Parray)[5] = 546;
将第 5 个元素分配给 546,结果是下面的表达式将执行的操作。
arr[5] = 546;
如图所示here .
关于C++ 入门 - 数组的指针和引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41665810/