繁体   English   中英

访问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

}

同样在C语言中,数组会衰减为指针。

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

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

所以:

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

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

与间接运算符之间的等价如下

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

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

让我们检查数据类型。

  • 对于int *ap[m]; apint * s的数组。 对于函数参数int*ap[]ap是指向int指针的指针。

  • 然后, ap[k] (指的是上一点)是一个int * 这很可能是已分配的内存,可以提供对多个int的有效访问。

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

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

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

相当于

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM