为什么不能用双指针来表示二维数组? [英] Why can't we use double pointer to represent two dimensional arrays?

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

问题描述

为什么不能用双指针来表示二维数组?

Why can't we use double pointer to represent two dimensional arrays?

arr[2][5] = {"hello","hai"};
**ptr = arr;

这里为什么双指针(**ptr)在这个例子中不起作用?

Here why doesn't the double pointer (**ptr) work in this example?

推荐答案

我要尝试如何画

int array[10][6];

int **array2 = malloc(10 * sizeof *array2);
for (int i = 0; i < 10; ++i)
    array2[i] = malloc(6 * sizeof **array2);

在记忆中的样子以及它们的不同之处(并且它们不能相互转换)

look like in the memory and how they are different (And that they can't be cast to each other)

array 看起来像:

 _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
| | | | | | | | | | | | | ..............| | | (10*6 elements of type int)
 - - - - - - - - - - - - - - - - - - - - - -
< first row >< second row> ...

array2 看起来像:

 _ _ _ _ _ _ _ _ _ _ 
| | | | | | | | | | | (10 elements of type int *)
 - - - - - - - - - - 
 | |     ....      |     _ _ _ _ _ _
 | |                -->| | | | | | | (6 elements of type int)
 | |                     - - - - - -
 | |
 | |      _ _ _ _ _ _
 |   -->| | | | | | | (6 elements of type int)
 |        - - - - - -
 |
 |
 |      _ _ _ _ _ _
   -->| | | | | | | (6 elements of type int)
        - - - - - -

当你说array[x][y]时,它转化为*((int *)array+x*6+y)

虽然,当你说 array2[x][y] 时,它会转化为 *(*(array2+x)+y) (注意对于 array,这个公式也有效(读到文章末尾,然后是评论)).

While, when you say array2[x][y], it translates into *(*(array2+x)+y) (Note that for array, this formula also works (read to the end of the post, and then the comments)).

也就是说,静态二维数组实际上是一个一维数组,行放在一行中.索引的计算公式为row * number_of_columns_in_one_row + column.

That is, a static 2d array is in fact a 1d array with rows put in one line. The index is calculated by the formula row * number_of_columns_in_one_row + column.

动态二维数组只是一个一维指针数组.然后每个指针被动态分配以指向另一个一维数组.事实上,那个指针可以是任何东西.可以是 NULL,或者指向单个变量,或者指向另一个数组.每个指针都是单独设置的,因此它们可以具有不同的性质.

A dynamic 2d array, however is just a 1d array of pointers. Each pointer then is dynamically allocated to point to another 1d array. In truth, that pointer could be anything. Could be NULL, or pointing to a single variable, or pointing to another array. And each of those pointers are set individually, so they can have different natures.

如果你需要将array的指针传递到某个地方,你不能将它转换为int **(想象一下会发生什么.int<array 的单元格的/code> 值被解释为指针并取消引用 -> Bam!分段错误!).但是,您可以将 array 视为 int [6] 的一维数组;这是一个一维元素数组,类型为 int [6].要写下来,你说

If you need to pass the pointer of array somewhere, you can't cast it to int ** (imagine what would happen. The int values of the cells of array are interpreted as pointers and dereferenced -> Bam! Segmentation fault!). You can however think of array as a 1d array of int [6]s; that is a 1d array of elements, with type int [6]. To write that down, you say

int (*p)[6] = array;

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

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