C中的2D数组如何成为1D数组? [英] How do 2D arrays in C become 1D arrays?

查看:250
本文介绍了C中的2D数组如何成为1D数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有人可以向我解释以下行为,我将非常感激:



说我声明一个静态2D数组

  float buffer [NX] [NY]; 

现在,如果我想填充这个数组,我注意到可以这样做:

  initarray(buffer,NX,NY); 

#define INITDATAVAL 0.5

void initarray(void * ptr,int nx,int ny)
{
int i,j;

float * data =(float *)ptr;

for(i = 0; i {
data [i] = INITDATAVAL;我的问题是,如果buffer是一个二维数组,那么我们可以使用一个数组,一旦传递到 initarray 函数,它如何用作一维数组?我很难理解...



当2D数组被静态分配时,分配的内存是连续的,但是如果

解决方案

具有3 x 4个元素的2D数组)在内存中如下:

  A1 A2 A3 A4 B1 B2 B3 B4 C1 C2 C3 C4 

由于底层存储是连续的,可以简单地将数组转换为指向第一个元素的指针,并使用单个偏移( buffer 传递给 initarray )。



(在此示例中,编译器会将 buffer [n] [m] code> buffer + n * NY + m 基本上,二维数组只是存储在一维数组中的二维数据的一个舒适的符号)。


I would appreciate if someone could explain to me the following behavior:

Say I declare a static 2D array

float buffer[NX][NY];

Now, if I want to populate this array, I have notice that it could be done this way:

initarray(buffer, NX, NY);

#define INITDATAVAL 0.5

void initarray(void *ptr, int nx, int ny)
{
  int i, j;

  float *data = (float *) ptr;

  for (i=0; i < nx*ny; i++)
    {
      data[i] = INITDATAVAL;
    }
}

My question is, if buffer is a 2D array, how can it be used as a 1D array once it is passed to initarray function? I am struggling to understand it...

When 2D arrays are statically allocated, the memory allocated is contiguous, but could this way be used if buffer is dynamically allocated instead?

解决方案

A 2D array with 3 x 4 elements (i.e. a matrix) looks like this in memory:

A1 A2 A3 A4 B1 B2 B3 B4 C1 C2 C3 C4

Since the underlying storage is continuous, one can simply convert the array to a pointer to the first element and access all elements using a single offset (this 'cast', which is called 'decaying' in such a context, happens automatically when buffer is passed to initarray).

(In this sample, the compiler would translate an expression such as buffer[n][m] to buffer + n*NY+m Basically, 2D arrays are just a comfortable notation for 2D data stored in 1D arrays).

这篇关于C中的2D数组如何成为1D数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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