Website For Developers

Pointers in C++



Syntax

dataType *variableName;
//for example
int *ptr;

Example of Pointers in C++

#include<iostream>
#include<conio.h>
using namespace std;
int main() {
  int number = 33;
  int *pointer;
  pointer = &number;
  cout<<"Address of number is: "<<pointer;
  getch();
  return 0;
}

Output

Address of number is: 0x22ff44



Example of asterisk * in Pointers

* is used to access the value of variable whose address is stored in the pointer.

#include<iostream>
#include<conio.h>
using namespace std;
int main() {
  int var;
  int * ptr;// pointer variable declaration
    //store the address of var in the pointer variable
  ptr = &var;
  cout<<"Enter value: ";
  cin>>var;
  cout<<endl;
    // Display the address stored in the pointer
  cout<<"Memory address of entered value is: ";
  cout<<ptr<<endl<<endl;
    // accessing the value of the address in the pointer
  cout<<"Pointer value is: ";
  cout<<*ptr<<endl<<endl;
  getch();
  return 0;
}

Output

Enter value: 125


Memory address of entered value is: 0x22ff44


Pointer value is: 125



Example#2: Pointers in C++

#include<iostream>
#include<conio.h>
using namespace std;
int main() {
  int var1, var2, total;
  int *ptr1, *ptr2;
  ptr1 = & var1;
  ptr2 = & var2;

  cout<<"Enter first integer value: ";
  cin>>*ptr1;
  cout<<"Enter second integer value: ";
  cin>>*ptr2;
  total = *ptr1 + *ptr2;
  cout<<"Total is: "<<total;
  getch();
  return 0;
}

Output

Enter first integer value: 535
Enter second integer value: 654
Total is: 1189


Advantages of Pointers