Friday, August 29, 2014

pointer to pointer ( double pointer )

  • example program(passing single pointer to function and chaning the single pointer value in the called functi

root@selvakumar-Lenovo-B460e:/C_pgms/double_pointer# cat dptr.c #include<stdio.h> int func(int **pointer_to_pointer); int main() { int a=10; int *ptr,**pptr; ptr = (int *) &a; pptr = &ptr; printf("\nvalue in *ptr =%d\n",*ptr); func(&ptr); printf("\nvalue in *ptr after func call =%d\n",*ptr); return 0; } int func(int **pointer_to_pointer) // to hold the address of another pointer { printf("\nvalue in pointer_to_pointer =%d\n",**pointer_to_pointer); **pointer_to_pointer = 20; } root@selvakumar-Lenovo-B460e:/C_pgms/double_pointer# gcc dptr.c root@selvakumar-Lenovo-B460e:/C_pgms/double_pointer# ./a.out value in *ptr =10 value in pointer_to_pointer =10 value in *ptr after func call =20 root@selvakumar-Lenovo-B460e:/C_pgms/double_pointer#


Passing double pointer to function:
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);
}


No comments:

Post a Comment