为什么我们不能用双指针重新present二维数组? [英] Why can't we use double pointer to represent two dimensional arrays?

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

问题描述

为什么我们不能用双指针重新present二维数组?

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

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

下面为什么在这个expample不是双指针(** PTR)工作的?

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

推荐答案

我要尝试绘制如何

int array[10][6];

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

看起来像内存以及​​它们是如何不同(他们不能投给对方)

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

阵列如下:

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

数组2 如下:

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

当你说数组[X] [Y] ,其转换成 *(((INT *)阵列)+ X * 6 + Y)

虽然,当你说数组2 [X] [Y] ,其转换成 *(*(数组2 + X)+ Y)

While, when you say array2[x][y], it translates into *(*(array2+x)+y)

即,一个静态二维数组实际上是一个一维阵列中放置了一行的行。该指数的计算公式行* number_of_columns_in_one_row +列

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.

如果您需要传递数组的指针的地方,你不能将它转换为 INT ** (想象一下会发生什么。阵列的细胞 INT 值间preTED为指针并取消引用 - >巴姆分段故障)!。然而,你可以把阵列作为一维数组 INT [6] S;这是元素的一维数组,类型 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;

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

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