简单数组初始化填充在 Linux (CentOS) 中有效,但在 Windows 中无效

Simple array initialization-population works in Linux (CentOS), but not in Windows

我在 C 中有一个简单的初始化填充例程,在 Linux 中工作正常。但是,当我尝试在 Code::Blocks 中 运行 它时,它会产生分段错误。

代码如下:

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

double **rho, **ux, **uy;
double** allocate_double_array(int nx, int ny)
{
   int i;
   double** array=(double**) malloc( (nx * sizeof(double*)) + (nx*ny * sizeof(double**)) );

   if (array==NULL) printf("Memory allocation failed!\n");

   for(i=0; i<nx; ++i)
   {
       array[i] = (double*)(array + nx) + i * ny;
   }
   return array;
}

int main()
{
    int nx = 100;
    int ny = 100;
    int x,y;

    rho   = allocate_double_array(nx,ny);
    ux    = allocate_double_array(nx,ny);
    uy    = allocate_double_array(nx,ny);

    printf("Memory allocated_alter\n");
    for (x=0; x<nx; x++)
    {
        for (y=0; y<ny; y++)
        {
            rho[x][y] = 1.0;
            ux[x][y] = 2.0;
            uy[x][y] = 3.0;
        }
    }
    printf("Initialization Complete\n");
    return 0;
}

知道我哪里出错了吗?

在双重分配函数中。

为什么要这样使用 malloc 函数?

尝试

double** array=(double**) malloc( (nx * sizeof(double*));

然后在循环中

array[i]=(double*)malloc( (ny * sizeof(double));