将三重指针传递给函数然后mallocing一个二维数组

时间:2016-01-31 17:06:04

标签: c arrays pointers malloc

出现细分错误并且不明白为什么,必须传递三重指针才能进行分配,因此无法改变...

这是功能

    void alloc2d(double*** a, int m, int n) {
     int i, j;

     **a  = malloc(sizeof(double *) * m);
     a[0] = malloc(sizeof(double) * n * m);

     for(i = 0; i < m; i++)
      a[i] = (*a + n * i);
    }

这里是函数的调用...

double** m;
alloc2d(&m, 5, 10);

double count = 0.0;

for (int i = 0; i < 5; i++)
    for (int j = 0; j < 10; j++)
        m[i][j] = ++count;

for (int i = 0; i <  5; i++)
    for (int j = 0; j < 10; j++)
        printf("%f ", m[i][j]);

1 个答案:

答案 0 :(得分:4)

您想为a所指的指针分配内存。将**a = malloc(sizeof(double *) * m);更改为*a = malloc(sizeof(double *) * m);。你为a[0]分配了内存,所以用索引1开始你的循环。与a[0]类似的*a类型为double**,但您希望将a[0]引用的指针设置为a[0]。将(*a)[0]更改为a[i],将(*a)[i]更改为void alloc2d(double*** a, int m, int n) { *a = malloc( sizeof( double* ) * m ); // allocate the memory for (m) double* (*a)[0] = malloc( sizeof(double) * n * m ); // allocate the linearized memory for (n*m) double for( int i=1; i<m; i++ ) (*a)[i] = (*a)[0] + n*i; // initialize the pointers for rows [1, m[ } 。像这样调整你的代码:

void alloc2d(double*** a, int m, int n) {

     double **temp = malloc( sizeof( double* ) * m ); // allocate the memory for (m) double*

     temp[0] = malloc( sizeof(double) * n * m );      // allocate the linearized memory for (n*m) double
     for ( int i=1; i<m; i++ )
         temp[i] = temp[0] + n*i;                     // initialize the pointers for rows [1, m[

     *a = temp;                                       // assign dynamic memory pointer to output parameter
}

我认为这会更容易理解:

Bash