无法理解指向固定大小数组的指针

Can't understand a pointer to a fixed size array

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

我是c++的新手,无法弄清楚指针指向固定大小的数组是如何工作的。

我正在读的那本书说:

short tell[10];
short (*pas)[20] = &tell;  //pas points to array of 20 shorts
...Thus, the type of pas is short(*)[20]. Also note that because pas is set to
&tell, *pas is equivalent to tell, so (*pas) [0] would be the first element of the array.

我不明白的是,"如果pas,被设置为&tell, *pas相当于tell。因此,(*pas)[0]是数组的第一个元素。"

我不明白if pas如何被设置为&tell,这是一个20字节内存块的地址,而*pas相当于tell。这意味着(*pas)[0]将是数组的第一个元素。

这是我第一次看到这种指针,所以我真的不明白它是如何工作的。

如果这是一个愚蠢的问题,我道歉。

谢谢。

数组是c++中的一种对象类型,因此可以使用指向数组的指针或指向数组的引用。在许多上下文中,数组的名称衰变为指向其第一个元素的指针,但它是而不是只是指向其第一个元素的指针。例如,给定int a[10]; int* i;,则sizeof(a)sizeof(int) * 10,并且几乎可以肯定等于sizeof(i)

声明指向数组的指针的语法是你们书中展示的难看的语法:

 short (*pas)[20]; // declare pas as a pointer to an array of 20 shorts
                   // pas is a single pointer

完全不同
 short *foo[20];   // declare foo as an array of 20 pointers to short
                   // foo is an array containing 20 pointers

你可以把数组的地址赋值给指向数组的指针,就像你可以把int变量的地址存储在指向int的指针中:

 short stuff[20];
 pas = &stuff;      // pas now points to the array stuff

你可以写一个通过引用接受数组的函数:

 void f(short (&arr)[20]) { } // f takes an array of 20 shorts by reference
 short p[20];
 short *i = p;   // p decays to a pointer to its first element in this context,
                 // and the resulting pointer is used to initialize i
 f(p);           // ok, pass the array by reference
 f(i);           // compile error
现在,示例中的代码是
short tell[10];
short (*pas)[20] = &tell;  //pas points to array of 20 shorts

不能编译,因为&tell的类型是"指向10个short s的数组的指针",不能赋值给类型为"指向20个short s的数组的指针"的变量。

假设我们修复了以下代码:

short tell[20];
short (*pas)[20] = &tell;  // now compiles! yay!

那么pas是一个指向20个short的数组的指针,它指向数组tell。解引用一个"指向T的指针"会得到指针指向的T,所以用*pas解引用pas会得到pas指向的20个short的数组。然后可以像其他数组一样对该数组使用下标操作符,记住[]*具有更高的优先级,因此需要使用括号:

short c = (*pas)[0];   // initializes c with the first element of the array pas points to
                       // since pas points to tell, this initializes c with tell[0].