【问题标题】:access to an array of pointers in c访问c中的指针数组
【发布时间】:2016-04-21 04:16:57
【问题描述】:

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

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

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 arrays pointers dereference pointer-to-pointer


    【解决方案1】:

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

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

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

    【讨论】:

    • 那么第二个索引访问的是指针指向的元素?
    【解决方案2】:

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

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

    等价于

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

    【讨论】:

      【解决方案3】:

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

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

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

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

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

      【讨论】:

        【解决方案4】:

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

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

        除非它是 sizeof 运算符的操作数或一元 & 运算符,或者是用于初始化数组的字符串文字, 具有“类型数组”类型的表达式被转换为 类型为“类型指针”的表达式,指向初始 数组对象的元素,不是左值。

        所以:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-18
          • 2013-02-13
          • 1970-01-01
          相关资源
          最近更新 更多