Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: How to pass a double pointer to a function

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.....

like image 432
veda Avatar asked Dec 02 '10 19:12

veda


3 Answers

Like others have said, you need to take a pointer to pointer to pointer in your init function. This is how the initialize function changes:

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

And main will be:

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

Also, the code as you posted it should cause no segmentation fault when passing the A pointer in. The segmentation fault most likely occurs when you return from the function and try to access A, because the A in main will not have been initialized. Only a copy of it is initialized the way you do it, and that copy is local to the initialize function, so it's lost when you return.

like image 200
IVlad Avatar answered Oct 05 '22 09:10

IVlad


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);
like image 37
Šimon Tóth Avatar answered Oct 05 '22 11:10

Šimon Tóth


Well for one thing, the A inside initialize is a copy of the A in main -- so when you get back to main, its A is still uninitialized. If you try and use it -- boom!

To pass it to initialize 'by reference', you need to change the parameter type to double*** and pass in &A in main. Then, when you use it in initialize, you need to dereference it each time, i.e. *A.

like image 1
Stuart Golodetz Avatar answered Oct 05 '22 10:10

Stuart Golodetz