C: How to pass a double pointer to a function

veda picture veda · Dec 2, 2010 · Viewed 56.3k times · Source

I am getting an segmentation fault when I pass the double pointers to the function to initialize the memory

int main()
{
    double **A;
    initialize(A, 10, 10);
 ......
}

void initialize(double **A, int r, int c)
{
   A = (double **)malloc(sizeof(double *)*r);
   for(int i = 0; i< r; i++) {
        A[i] = (double *)malloc(sizeof(double) *c);
        for(int j = 0; j < c; j++) {
            A[i][j] = 0.0;
        }
   }
}

How can I pass the double pointers to the functions.....

Answer

Šimon T&#243;th picture Šimon Tóth · Dec 2, 2010

If you want to modify a pointer to pointer you need to pass a pointer to pointer to pointer.

void func(double ***data) { *data = malloc(sizeof(double*)*10); for.... };
double ** data; func(&data);