我需要动态创建一个二维连续数组,在我的代码中声明为“x
”(更精确地声明为 double **x
,如下所示)和
size of 2D array = [size_tot_y, size_tot_x] = [number of lines, number of columns]
这是我所做的:
/* 2D Array */
double **x;
/* 1D array */
double *x_vals;
/* Allocating arrays */
x = malloc(size_tot_y*sizeof(*x));
x_vals = malloc(size_tot_x*size_tot_y*sizeof(*x_vals));
/* Make x contiguous */
for (j=0;j<=size_tot_y-1;j++)
x[j] = &x_vals[j*size_tot_x];
此代码片段是否可以使 x[i][j]
数组连续?
感谢您的评论。
最佳答案
Is this code snippet correct for making x[i][j] array contiguous ?
是的,从 x[0][0]
到 x[rows - 1][cols - 1]
的所有数据都在连续区域中。
请注意,第二个 malloc
不需要另一个指针,我建议:
x = malloc(size_tot_y * sizeof(*x));
x[0] = malloc(size_tot_x * size_tot_y * sizeof(**x));
for (j = 1; j < size_tot_y; j++)
x[j] = x[0] + j * size_tot_x;
如果您使用的是 C99 或 C11,您可以使用指向 VLA 的指针一步完成 malloc
:
double (*x)[size_tot_x];
x = malloc(sizeof(double [size_tot_y][size_tot_x]));
关于c - 需要验证以创建连续数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44186415/