2

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

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

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

}
4

4 回答 4

2

同样在 C 中,数组被称为衰减为指针。

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

除非它是 sizeof 运算符或一元 & 运算符的操作数,或者是用于初始化数组的字符串文字,否则类型为 ''array of type'' 的表达式将转换为类型为 ''pointer to type'' 指向数组对象的初始元素并且不是左值。

所以:

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])。

于 2016-01-15T14:40:02.843 回答
1

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

让我们检查数据类型。

  • 因为int *ap[m];,apint *s 的数组。在函数参数的情况下int*ap[]ap是指向 int 指针的指针。

  • 那么,ap[k](参考上一点)是一个int *. 这很可能是分配的内存,可以提供对多个ints 的有效访问。

  • 如果分配了足够的内存,ap[k][s]将引用一个int.

于 2016-01-15T14:34:17.530 回答
1

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

它与间接运算符之间的等效性如下

pointer[i] == *(pointer + i);
于 2016-01-15T14:32:10.990 回答
0

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

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

相当于

int* dosomethingwithmatrix(const int **ap, int **bp)
于 2016-01-15T14:33:20.690 回答