Saturday 21 October 2017

double pointers

int **ptr;    // declaring double pointers
Below diagram explains the concept of Double Pointers:
pointer2pointer When will use double pointer?
Use ** when you want to preserve (OR retain change in) the Memory-Allocation or Assignment even outside of a function call.

void alloc2(int** p) {
   *p = (int*)malloc(sizeof(int));
   **p = 10;
  printf("address(alloc2):%p and value %d\n ",*p,**p);
  //Output: address(alloc2):0x1c54440 and value 10

void alloc1(int* p) {
   p = (int*)malloc(sizeof(int));
   *p = 10;
  printf("address(alloc1):%p and value %d\n ",p,*p);

// Output: address(alloc1):0x1c54010 and value 10

int main(){
   int *p1,*p2;
   //Pass by value
   alloc1(p1);

   printf("address:%p and value %d\n ",p1,*p1);//value is undefined
 //Output:  address:0x7fffebb11160 and value 1
  
//Pass by reference
  alloc2(&p2);
   printf("addres:%p and value:%d\n ",p2,*p2); 
  //output:   addres:0x1c54440 and value:10
   free(p2);
   return 0;
}

No comments:

Post a Comment