c - 需要验证以创建连续数组

标签 c arrays

我需要动态创建一个二维连续数组,在我的代码中声明为“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/

相关文章:

c - fgets c 标准库函数

c - 取消引用指针和访问数组元素之间的区别

python - 优化双for循环以查找二维数组上特定值的计数

C - 将结构成员的地址传递给函数错误返回

c++ - 从 C/C++ 代码执行 RDMSR 和 WRMSR 指令

c - 如何同时返回 bool 和 double?

使用 & 和不使用 & 的 C 3d 数组指针衰减

c++ - 如何从类中返回自定义数组项并操作其属性? C++

arrays - MongoDB:匹配数组元素的计数

c# - 如何在 python 3 中解码由 C# Convert.ToBase64String 编码的字符串