如何在C中使用动态多维数组?

如何在C中使用动态多维数组?,c,arrays,dynamic,C,Arrays,Dynamic,有人知道如何使用C动态分配多维数组吗?这可能吗?使用malloc动态分配: int** x; x = malloc(dimension1_max * sizeof(*x)); for (int i = 0; i < dimension1_max; i++) { x[i] = malloc(dimension2_max * sizeof(x[0])); } //Writing values x[0..(dimension1_max-1)][0..(dimension2_max-1)]

有人知道如何使用C动态分配多维数组吗?这可能吗?

使用malloc动态分配:

int** x;

x = malloc(dimension1_max * sizeof(*x));
for (int i = 0; i < dimension1_max; i++) {
  x[i] = malloc(dimension2_max * sizeof(x[0]));
}

//Writing values
x[0..(dimension1_max-1)][0..(dimension2_max-1)] = Value; 
[...]

for (int i = 0; i < dimension1_max; i++) {
  free(x[i]);
}
free(x);
基础 c中的数组是使用
[]
操作符声明和访问的。所以

int ary1[5];
声明一个由5个整数组成的数组。元素从零开始编号,因此
ary1[0]
是第一个元素,而
ary1[4]
是最后一个元素。注1:没有默认初始化,因此数组占用的内存最初可能包含任何内容。注2:
ary1[5]
以未定义的状态访问内存(您甚至可能无法访问),所以不要这样做

多维数组被实现为数组的数组(数组的数组…)。所以

声明一个由3个一维数组组成的数组,每个数组包含5个浮点数。现在,
ary2[0][0]
是第一个数组的第一个元素,
ary2[0][4]
是第一个数组的最后一个元素,
ary2[2][4]
是最后一个数组的最后一个元素。89年的标准要求这些数据是连续的(我的K&R第二版第216页第A8.6.2节),但似乎对填充是不可知的

尝试在多个维度中动态化 如果在编译时不知道数组的大小,则需要动态分配数组。尝试是很有诱惑力的

double *buf3;
buf3 = malloc(3*5*sizeof(double));
/* error checking goes here */
如果编译器不填充分配(在一维数组之间留有额外的空间),这应该可以工作。使用以下设备可能更安全:

double *buf4;
buf4 = malloc(sizeof(double[3][5]));
/* error checking */
但无论哪种方式,技巧都是在解引用时出现的。无法写入
buf[i][j]
,因为
buf
的类型错误。你也不能使用

double **hdl4 = (double**)buf;
hdl4[2][3] = 0; /* Wrong! */
因为编译器希望
hdl4
是一个double地址的地址。也不能使用
double completed_ary4[]因为这是一个错误

那你能做什么呢

  • 自己做行和列运算
  • 在函数中分配和执行工作
  • 使用指针数组(qrdl所讨论的机制)
你自己算吧 只需计算每个元素的内存偏移量,如下所示:

  for (i=0; i<3; ++i){
     for(j=0; j<3; ++j){
        buf3[i * 5 + j] = someValue(i,j); /* Don't need to worry about 
                                             padding in this case */
     }
  }
当然,在这种情况下,
ary4
是一个局部变量,不能返回它:数组的所有工作都必须在它调用的函数中调用的函数中完成

指针数组 考虑这一点:

double **hdl5 = malloc(3*sizeof(double*));
/* Error checking */
for (i=0; i<3; ++i){
   hdl5[i] = malloc(5*sizeof(double))
   /* Error checking */
}
double**hdl5=malloc(3*sizeof(double*);
/*错误检查*/
对于(i=0;imalloc就可以了

 int rows = 20;
 int cols = 20;
 int *array;

  array = malloc(rows * cols * sizeof(int));
请参阅以下文章以获取帮助:-


无法一次性分配整个内容。相反,创建一个指针数组,然后为每个指针创建内存。例如:

int** array;
array = (int**)malloc(sizeof(int*) * 50);
for(int i = 0; i < 50; i++)
    array[i] = (int*)malloc(sizeof(int) * 50);
但如果你不知道使用预处理器宏的效果,那就更糟糕了。

int rows,columns;
int rows, columns;
/* initialize rows and columns to the desired value */

    arr = (int**)malloc(rows*sizeof(int*));
        for(i=0;i<rows;i++)
        {
            arr[i] = (int*)malloc(cols*sizeof(int));
        }
/*将行和列初始化为所需的值*/ arr=(int**)malloc(rows*sizeof(int*);
对于(i=0;i自C99以来,C具有具有动态边界的2D数组。如果您希望避免在堆栈上分配此类beast(您应该这样做),您可以按如下方式一次轻松地分配它们

double (*A)[n] = malloc(sizeof(double[n][n]));
就是这样。然后你可以很容易地使用它,就像你在2D数组中使用类似于
A[i][j]
的东西一样。最后不要忘记这一点

free(A);

Randy Meyers写了一系列文章来解释。

如果您知道编译时的列数,那么它非常简单:

#define COLS ...
...
size_t rows;
// get number of rows
T (*ap)[COLS] = malloc(sizeof *ap * rows); // ap is a *pointer to an array* of T
size_t rows;
size_t cols;
// get rows and cols
T (*ap)[cols] = malloc(sizeof *ap * rows);
...
ap[i][j] = x;
...
free(ap);
您可以像对待任何2D阵列一样对待ap

ap[i][j] = x;
当你完成后,你将它作为

free(ap);
如果您不知道编译时的列数,但使用的是支持可变长度数组的C99编译器或C2011编译器,那么它仍然非常简单:

#define COLS ...
...
size_t rows;
// get number of rows
T (*ap)[COLS] = malloc(sizeof *ap * rows); // ap is a *pointer to an array* of T
size_t rows;
size_t cols;
// get rows and cols
T (*ap)[cols] = malloc(sizeof *ap * rows);
...
ap[i][j] = x;
...
free(ap);
如果您不知道编译时的列数,并且使用的是不支持可变长度数组的C版本,那么您需要做一些不同的事情,则可以将内存分配为1D数组,并计算1D偏移:

size_t rows, cols;
// get rows and columns
T *ap = malloc(sizeof *ap * rows * cols);
...
ap[i * rows + j] = x;
...
free(ap);
如果不需要连续的内存,可以遵循两步分配方法:

size_t rows, cols;
// get rows and cols
T **ap = malloc(sizeof *ap * rows);
if (ap)
{
  size_t i = 0;
  for (i = 0; i < cols; i++)
  {
    ap[i] = malloc(sizeof *ap[i] * cols);
  }
}

ap[i][j] = x;
size\u t行,cols;
//吵架
T**ap=malloc(sizeof*ap*行);
如果(ap)
{
尺寸i=0;
对于(i=0;i
由于分配是一个两步过程,因此解除分配也需要是一个两步过程:

for (i = 0; i < cols; i++)
  free(ap[i]);
free(ap);
(i=0;i 免费(ap[i]); 免费(ap);
这里是一个工作代码,它定义了一个子例程
生成3d数组
来分配多维3d数组,每个维度中有
N1
N2
N3
元素,然后用随机数填充。您可以使用符号
a[i][k]
来访问其元素

#include <stdio.h>
#include <stdlib.h>
#include <time.h>


// Method to allocate a 2D array of floats
float*** make_3d_array(int nx, int ny, int nz) {
    float*** arr;
    int i,j;

    arr = (float ***) malloc(nx*sizeof(float**));

    for (i = 0; i < nx; i++) {
        arr[i] = (float **) malloc(ny*sizeof(float*));

        for(j = 0; j < ny; j++) {
            arr[i][j] = (float *) malloc(nz * sizeof(float));
        }
    }

    return arr;
} 



int main(int argc, char *argv[])
{
    int i, j, k;
    size_t N1=10,N2=20,N3=5;

    // allocates 3D array
    float ***ran = make_3d_array(N1, N2, N3);

    // initialize pseudo-random number generator
    srand(time(NULL)); 

    // populates the array with random numbers
    for (i = 0; i < N1; i++){
        for (j=0; j<N2; j++) {
            for (k=0; k<N3; k++) {
                ran[i][j][k] = ((float)rand()/(float)(RAND_MAX));
            }
        }
   }

    // prints values
    for (i=0; i<N1; i++) {
        for (j=0; j<N2; j++) {
            for (k=0; k<N3; k++) {
                printf("A[%d][%d][%d] = %f \n", i,j,k,ran[i][j][k]);
            }
        }
    }

    free(ran);
}
#包括
#包括
#包括
//方法来分配二维浮点数组
浮点***生成3d数组(整数nx、整数ny、整数nz){
浮动***arr;
int i,j;
arr=(浮动***)malloc(nx*sizeof(浮动**));
对于(i=0;i对于(j=0;j//使用new而不是malloc,因为使用malloc会导致内存泄漏
`在这里输入代码

    int **adj_list = new int*[rowsize];       
    for(int i = 0; i < rowsize; ++i)    
    {

        adj_list[i] = new int[colsize];

    }
int**adj_list=newint*[rowsize];
对于(int i=0;i
这不会编译,您需要将x声明为“int**”,而不是“int[][]”。Wh
#include <stdio.h>
#include <stdlib.h>
#include <time.h>


// Method to allocate a 2D array of floats
float*** make_3d_array(int nx, int ny, int nz) {
    float*** arr;
    int i,j;

    arr = (float ***) malloc(nx*sizeof(float**));

    for (i = 0; i < nx; i++) {
        arr[i] = (float **) malloc(ny*sizeof(float*));

        for(j = 0; j < ny; j++) {
            arr[i][j] = (float *) malloc(nz * sizeof(float));
        }
    }

    return arr;
} 



int main(int argc, char *argv[])
{
    int i, j, k;
    size_t N1=10,N2=20,N3=5;

    // allocates 3D array
    float ***ran = make_3d_array(N1, N2, N3);

    // initialize pseudo-random number generator
    srand(time(NULL)); 

    // populates the array with random numbers
    for (i = 0; i < N1; i++){
        for (j=0; j<N2; j++) {
            for (k=0; k<N3; k++) {
                ran[i][j][k] = ((float)rand()/(float)(RAND_MAX));
            }
        }
   }

    // prints values
    for (i=0; i<N1; i++) {
        for (j=0; j<N2; j++) {
            for (k=0; k<N3; k++) {
                printf("A[%d][%d][%d] = %f \n", i,j,k,ran[i][j][k]);
            }
        }
    }

    free(ran);
}
    int **adj_list = new int*[rowsize];       
    for(int i = 0; i < rowsize; ++i)    
    {

        adj_list[i] = new int[colsize];

    }