passing a triple pointer into function then malloc

2019-09-20 19:56发布

问题:

Getting a segmentation fault and don't understand why, have to pass in triple pointer for assignment so can't change that...

Here's the function

    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);
    }

Here's the calling of the function...

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:

You want to allocate the the memory for the pointer where a refers to. Change **a = malloc(sizeof(double *) * m); to *a = malloc(sizeof(double *) * m);. You alraedy allocated the memory for a[0], so start your loop with index 1. The type of a[0] which is similar to *a is double**, but you want to set the pointer where a[0] refers to. Change a[0] to (*a)[0] and a[i] to (*a)[i]. Adapt your code like this:

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[
}

I think this would be more comprehensible:

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
}