如何动态分配一个连续的内存块的二维数组 [英] How to dynamically allocate a contiguous block of memory for a 2D array

查看:290
本文介绍了如何动态分配一个连续的内存块的二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我分配一个二维数组,像这样的 int类型的[N] [N] ;它会分配一个连续的内存块。

If I allocate a 2D array like this int a[N][N]; it will allocate a contiguous block of memory.

但是,如果我尝试动态做这样的:

But if I try to do it dynamically like this :

int **a = malloc(rows * sizeof(int*));
for(int i = 0; i < rows; i++) 
   a[i] = malloc(cols * sizeof(int));

这个保持的行中的元素之间的单元间距,但是这可能不是行之间的情况

This maintains a unit stride between the elements in the rows, but this may not be the case between rows.

解决方案之一是从2D转换成一维,除此之外,有另一种方式来做到这一点?

One solution is to convert from 2D to 1D, besides that, is there another way to do it?

推荐答案

如果您的阵列尺寸是在编译时已知:

If your array dimensions are known at compile time:

#define ROWS ...
#define COLS ...

int (*arr)[COLS] = malloc(sizeof *arr * ROWS);
if (arr) 
{
  // do stuff with arr[i][j]
  free(arr);
}

如果您的阵列尺寸不会在编译时已知,并且使用的是C99编译器或支持变长数组一个C2011编译器:

If your array dimensions are not known at compile time, and you are using a C99 compiler or a C2011 compiler that supports variable length arrays:

size_t rows, cols;
// assign rows and cols
int (*arr)[cols] = malloc(sizeof *arr * rows);
if (arr)
{
  // do stuff with arr[i][j]
  free(arr);
}

如果您的阵列尺寸不会在编译时已知,而且你的的使用C99编译器或支持变长数组一个C2011编译器:

If your array dimensions are not known at compile time, and you are not using a C99 compiler or a C2011 compiler that supports variable-length arrays:

size_t rows, cols;
// assign rows and cols
int *arr = malloc(sizeof *arr * rows * cols);
{
  // do stuff with arr[i * rows + j]
  free(arr);
}

这篇关于如何动态分配一个连续的内存块的二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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