Thursday, 21 September 2017

Pointer to pointer demo in C++

/*
 Pointer to Pointer Demo in C++
*/

#include "iostream"
using namespace std;

int globalN=20;

void pointerToPointer(int **newp){
 *newp = &globalN;
}
 
 int main(){
 int n=10;
 int *p = &n;
 cout<<"\nLocal N: "<<*p; //prints 10
 int **ptr = &p;
 cout<<"\n"<<*ptr; // print address  
 cout<<"\n"<<**ptr; // prints 10
 pointerToPointer(&p); // call to function which takes pointer to pointer argument

 cout<<"\n"<<*p<<endl; // prints 20
}
/*
 OUTPUT
[pavan@localhost Pointers]$ g++ P-P.cpp
[pavan@localhost Pointers]$ ./a.out 

Local N: 10
0x7ffcbdaf12e4
10
20
[pavan@localhost Pointers]$ 
*/

No comments: