为什么我不能一个二维数组转换在C二维指针? [英] Why can't I convert a two-dimensional array to a two-dimensional pointer in C?

查看:198
本文介绍了为什么我不能一个二维数组转换在C二维指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么下面的程序给出一个的转换:不能从int转换[1] [1]为int ** 错误?我用VS2008编译在Windows 7下。

  INT的main(){
    诠释一个[1] [1] = {0};
    INT ** P = A;
}


解决方案

您只能转换数组指针一次。该指针==阵列抽象断裂从第二级开始。

您可以做

  INT(* P)[1] = A; //转换长度为1的数组的数组
                 //的指针长度为1的阵列

但它变得清晰,如果你看到在每种情况下的内存布局,你不能多维数组转换为指针到指针:

  //多维数组(一[] [])
一个 - > [第一行] [第二行] [...]//指针的指针(** P)
对 - > [P0] [P1] [P2]
      | | |
      | | \\ - > [第三排]
      | \\ -----> [第二排]
      \\ ----------> [第一排]

在指针到指针的方法的行并不一定是连续的,并需要有用于指向各行脊椎的额外阵列。

Why does the following program give a 'conversion' : cannot convert from int[1][1] to int** error? I am compiling with VS2008 under Windows 7.

int main(){
    int a[1][1] = {0};
    int **p = a;
}

解决方案

You can only convert arrays to pointers one time. The "pointers == arrays" abstraction breaks from the second level onwards.

You can do

int (*p)[1] = a; //convert an array of arrays of length 1
                 // to a pointer to arrays of length 1

But it becomes clear you cannot convert multidimentional arrays to pointers-to-pointers if you see the memory layout in each case:

//multidimentional arrays (a[][])
a -> [first row][second row][...]

//pointers to pointers (**p)
p -> [p0][p1][p2]
      |    |   |
      |    |   \-> [third row]
      |    \-----> [second row]
      \----------> [first row]

In the pointer-to-pointer approach the rows are not necessarily contiguous and there needs to be an extra array for the spine that points to the individual rows.

这篇关于为什么我不能一个二维数组转换在C二维指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆