c - 为什么在 C 中不能将二维数组转换为二维指针?

标签 c arrays pointers

为什么以下程序会给出 'conversion' :无法从 int[1][1] 转换为 int** 错误?我在Windows 7下用VS2008编译。

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

最佳答案

您只能将数组转换为指针一次。 “指针==数组”抽象从第二级开始中断。

你可以做到

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

但是如果您看到每种情况下的内存布局,很明显您无法将多维数组转换为指针到指针:

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

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

在指针到指针方法中,行不一定是连续的,并且需要有一个额外的数组用于指向各个行的脊柱。

关于c - 为什么在 C 中不能将二维数组转换为二维指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8264392/

相关文章:

arrays - 查找数组中所有元素实例的索引

c - 使用 fscanf 无法按预期读取文件

c - 在 C 中监视 stdin、stdout 和 stderr 中的字节

c - 打印 sqlite3_exec 错误消息导致 C 中的段错误

php - 如何在此代码中生成我期望的 json

C++编译器错误: passing pointers but compiler sees references

C:比较结构中的两个字符串

arrays - 显式形状数组 reshape 的警告

c++ - 使用指针访问struct c++ vector 中的元素

objective-c - 我很困惑。我的代码有什么问题?关于 malloc 和函数将指针传递给指针