一维数组衰变为指针,但二维数组不这样做,为什么呢? [英] 1D array decays to pointer, but 2D array doesn't do so, why?

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

问题描述

有人能解释我为什么在技术上的二维数组实际上并不衰减到 INT ** ,而当你有一个维数组,你得到的指针衰减到为int * (如果你有阵 INT )。

Can someone explain to me why technically a 2D array does not actually decay to int** whereas when you have a single dimensional array, you do get pointer decay to int* (if you had array of int).

我明白指针衰减是什么,但我不明白为什么二维数组不会出现这种衰变?

I understand what pointer decay is, but I don't get why the 2D array doesn't exhibit this decay?

这是一个与人新的C或C ++一个共同的困惑,但我发现自己绊倒它往往过​​于

It's a common confusion with people new to C or C++, but I find myself tripping over it often too.

推荐答案

他们有不同的内存布局。二维数组是一个连续的内存块,而 INT ** 是指针数组。随着二维数组,偏移到一个位置被计算为的rownum * collength + colnum (或取决于你如何标注行/列上反之亦然)。这不会与工作INT ** ,这实际上产生了两个内存读取;第一个获得的列指针,然后在一个从该存储器偏移数据的读出

They have different memory layouts. A 2D array is one contiguous piece of memory while int** is an array of pointers. With a 2D array, the offset into a location is computed as rownum * collength + colnum (or vice versa depending on how you label rows/columns). That would not work with int**, which actually produces two memory reads; the first to get the column pointer, then the read of the data at an offset from that memory.

这不同的布局,顺便说一下,为什么你必须声明数组尺寸(所有,但最左侧)在接受二维数组功能;否则不可能让编译器生成code来计算偏移。

This different layout is, incidentally, why you must declare the array dimensions (all but the left-most) in functions that accept 2D arrays; otherwise it would not be possible for the compiler to generate the code to compute the offsets.

以下是 INT ** 的内存布局的图片的尝试。左栏是指针的连续的阵列,其中每一个包含与该数据的连续块的存储器的地址。请注意,在每列中的数据不必具有相同的长度(虽然不一定是为code可读性一件好事):

The following is an attempt at a picture of the memory layout of int**. The left column is a contiguous array of pointers where each contains the address of a contiguous piece of memory with the data. Note that the data in each column does not have to be the same length (although that might not necessarily be a good thing for code readability):

int **array; 
int i, j;
int cntr = 1;
array = malloc( 3 * sizeof( int* ));
for ( i = 0; i < 3; i++ ) {
   array[i] = malloc( 4 * sizeof( int ));
   for ( j = 0; j < 4; j++ )
      array[i][j] = cntr++;
   }

给出这样的:

array ==> |addr1|  ==>  [1,2,3,4]
          |addr2|  ==>  [5,6,7,8]
          |addr3|  ==>  [9,10,11,12]

在此相反,这是布局可能看起来像 INT [3] [4] 。括号只显示数据的每个列的逻辑断点。这些整数值是在内存中连续的:

In contrast, This is what the layout might look like for int[3][4]. The brackets just show the logical break of each column of data. The integer values are contiguous in memory:

int array[3][4];
int i, j;
int cntr = 1;
for ( i = 0; i < 3; i++ )
   for ( j = 0; j < 4; j++ )
      array[i][j] = cntr++;

给出这样的:

array ==> [1,2,3,4][5,6,7,8][9,10,11,12]

这篇关于一维数组衰变为指针,但二维数组不这样做,为什么呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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