pointers to pointers c++ code example

Example 1: c++ pointers

#include <iostream>

using namespace std;

int main () {
   int  var = 20;   // actual variable declaration.
   int  *ip;        // pointer variable 

   ip = &var;       // store address of var in pointer variable

   cout << "Value of var variable: "; 
   cout << var << endl; //Prints "20"

   // print the address stored in ip pointer variable
   cout << "Address stored in ip variable: ";
   cout << ip << endl; //Prints "b7f8yufs78fds"

   // access the value at the address available in pointer
   cout << "Value of *ip variable: ";
   cout << *ip << endl; //Prints "20"

   return 0;
}

Example 2: c++ pointers

// my first pointer
#include <iostream>
using namespace std;

int main ()
{
  int firstvalue, secondvalue;
  int * mypointer; //creates pointer variable of type int

  mypointer = &firstvalue;
  *mypointer = 10;
  mypointer = &secondvalue;
  *mypointer = 20;
  cout << "firstvalue is " << firstvalue << '\n';   //firstvalue is 10
  cout << "secondvalue is " << secondvalue << '\n'; //secondvalue is 20
  return 0;
}

Example 3: pointers to pointers in cpp

#include <iostream>
 
using namespace std;
 
int main () {
   int  var;
   int  *ptr;
   int  **pptr;

   var = 3000;

   // take the address of var
   ptr = &var;

   // take the address of ptr using address of operator &
   pptr = &ptr;

   // take the value using pptr
   cout << "Value of var :" << var << endl;
   cout << "Value available at *ptr :" << *ptr << endl;
   cout << "Value available at **pptr :" << **pptr << endl;

   return 0;
}

Tags:

Cpp Example