访问c中的指针数组

access to an array of pointers in c

当定义为一维时,为什么我可以访问具有两个参数的指针数组?

我知道,我必须使用指针数组来访问函数中的多维数组,但我不知道为什么我可以使用两个参数访问指针数组。

int a[m][l] { 1,2,3,4, 2,3,4,5, 3,4,5,6  }; //some matrices
int c[m][l];    
int *ap[m];  //array of pointers one-dimensional
int i,j;


for (i = 0; i < m; i++)  //passing the address of first element in each 
        ap[i] = a[i];    //colon of matrix to array of pointers

for (j = 0; j < m; j++)
        bp[i] = b[i];

dosomethingwithmatrix(ap[0], bp[0], m, l);



int* dosomethingwithmatrix(const int*ap[], int* bp[])
{
            cp[i][j] = ap[i][j] //accss the array of pointers with two parameters

}

因为您可以使用索引符号取消引用指针。首先,您使用索引访问元素(指针),现在也可以使用索引取消引用指针。

它与间接运算符的等价关系如下

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

函数dosomethingwithmatrix的参数apbp都是指向int的指针。它们不是指针数组。函数声明符

int* dosomethingwithmatrix(const int *ap[], int *bp[])  

等同于

int* dosomethingwithmatrix(const int **ap, int **bp)

在你的情况下,ap[i][j] 是允许的,因为它很有意义。

让我们检查一下数据类型。

  • 对于int *ap[m];ap是一个int *的数组。在函数参数 int*ap[] 的情况下,ap 是指向 pointer-to-int.

  • 的指针
  • 那么,ap[k](指上一点)就是一个int *。这很可能是分配的内存,可以提供对多个 ints.

  • 的有效访问
  • 如果分配了足够的内存,ap[k][s] 将引用 int

同样在 C 中,据说数组 衰减 为指针。

来自标准(C99 6.3.2.1/3 - 其他操作数 - 左值、数组和函数指示符):

Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue.

所以:

array[i] "decays" to pointer[i]
where pointer has the address of the [0]th element of array

因为我们已经看到了:

p[i] == *(p + i)

我们所做的只是为指针添加偏移量。

顺便说一句,由于加法是可交换的,*(p + i) == *(i + p),它有时会给出令人惊讶的结果:

3["hello world"]

是一个完全有效的 C 表达式(它等于 "hello world"[3])。