数组中的指针语法用法

Pointer syntax usage in Array

我在理解二维数组上下文中的指针语法用法时遇到了一些问题,尽管我对一维数组表示法和指针很满意,但下面是其中一种语法,我无法理解以下内容表达式被评估。

要访问存储在数组 a 第三行第二列 的元素,我们将使用下标表示法 a[2][1] 访问同一元素的另一种方式是

*(a[2]+1)

如果我们想将它用作指针,我们会这样做

*(*(a+2)+1)

虽然我能够理解 *(a[2]+1) 的替换 as *(*(a+2)+1) 但我不知道这是如何评估的。 如果可能,请举例说明。 假设数组按行顺序存储并包含以下元素

int a[5][2]={
               21,22,
               31,32
               41,42,
               51,52,
               61,62
             };

数组的基地址是 100(假设) 所以 a[2] 的地址是 108 (int 的大小 =2(另一个假设)) 所以表达式 *(*(a+2)+1). How does it gets evaluated does it start from the inside bracket and if it does then after the first bracket we have the value to which 1 is being added rather than the address... :/

首先是

a[i] = *(a+i);

所以

a[i][j] = *(a[i] +j)

a[i][j] = *(*(a+i) + j) 

How a[i] = *(a+i):

如果 a 是数组,则数组的起始地址由 &a[0]a

给出

所以当你指定

a[i] 这将衰减为指针操作 *(a+i) 即从位置 a 开始并取消引用指针以获取存储在该位置的值。

如果内存位置为a,则存储在其中的值由*a给出。

同样,数组中下一个元素的地址由

给出
&a[1] = (a+1); /* Array decays to a pointer */

现在元素存储的位置由 &a[1](a+1) 给出,因此存储在该位置的值由 *(&a[1])*(a+1)[= 给出31=]

例如:

int a[3];

它们存储在内存中如下所示:

  a    a+1   a+2
------------------
| 100 | 102 | 104| 
------------------
 &a[0] &a[1] &a[2]

现在 a 指向数组的第一个元素。如果你知道指针操作 a+1 会给你下一个位置等等。

在二维数组中,访问方式如下:

int arr[m][n];



  arr:
        will be pointer to first sub array, not the first element of first sub 
        array, according to relationship of array & pointer, it also represent 
        the array itself,

    arr+1:
        will be pointer to second sub array, not the second element of first sub 
        array,

    *(arr+1):
        will be pointer to first element of second sub array,
        according to relationship of array & pointer, it also represent second
        sub array, same as arr[1],

    *(arr+1)+2:
        will be pointer to third element of second sub array,

    *(*(arr+1)+2):
        will get value of third element of second sub array,
        same as arr[1][2],

一个二维数组其实就是一段连续的内存。让我举个例子:int a[3][4] 在内存中由一个唯一的 12 位整数序列表示:

a00 a01 a02 a03 a04 a10 a11 a12 a13 a14 a20 a21 a22 a23 a24
|                   |                   |
first row           second row          third row

(当然可以推广到任意多维数组)

aint[4] 的数组:它 衰减 指向 int[4] 的指针(事实上,它衰减到 &(a[0]))

a[1] 是第二行。它 衰减 int * 指向第一行的开头。

即使数组不是指针,它们衰减为指针的事实也允许在指针算术中使用它们:a + 1 是指向数组 a 的第二个元素的指针。

所有这些都解释了为什么 a[1] == *(a + 1)

同样的推理可以应用于 a[i] == *(a+i),并从那里应用于您问题中的所有表达式。

让我们具体看一下*(*(a+2)+1)。如上所述,a + 2是指向int 4数组第三个元素的指针。所以 *(a + 2) 是第三行,是 int[4] 的数组并衰减到 int *&(a[2][0]).

由于 *(a + 2) 衰减为 int *,我们仍然可以将其用作指针运算的基础,而 *(a + 2) + 1 是指向第三行第二个元素的指针:*(a + 2) + 1 == &(a[2][1])。取消引用所有这些,我们得到

*(*(a + 2) + 1) == a[2][1]