cpp declare pointer code example

Example 1: 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 2: pointer in c++

int* pointVar, var;
var = 5;

// assign address of var to pointVar
pointVar = &var;

// access value pointed by pointVar
cout << *pointVar << endl;   // Output: 5

In the above code, the address of var is assigned to the pointVar pointer.
We have used the *pointVar to get the value stored in that address.

Tags:

Misc Example