< C++ Tutorial

C++ pointers

← Previous Next →

Pointers are one of the stongest features of C++ progamming language. A pointer provides a way to directly access memory of a variable directly. 

What is a Pointer?

A pointer is a variable, which contains the address of a memory location of another variable. If one variable contains the address of another variable, the first variable is said to point to the second. 


data-type * variable-name;

Example :

int *ptr ; // pointer to int
double *ptr ; // pointer to double
char *ptr ; //pointer to char 

This define a pointer variable ptr . Where * is used to denote that variable is a integer pointer variable.

Applications of Pointers:

Pointers are used in the situtions when passing actual values is difficult or not desired. Few of the situations where pointers can be used are:

  • To return more than one value from a function.
  • To pass arrays and strings more conveniently from one function to another.
  • To allocate memory and access it.
  • To create complex data structures, such as linked lists, where one data structure must contain referrences to other data structures.

Pointers are used to directly access the memory using address and manipulate the data.

How to use Pointer

Assigning address to any pointer

 &   operator is used fot getting address

int  id  = 4 ; 
int *ptr = NULL; 
p = &id; //It will give address(memory location) of variable id to p .

In below example address of variable id is assigned to ptr1 and ptr2

int main()
  int id=5;
  int *ptr1 = id ; // if assignment is done on variable definition line
  int *ptr2 ;
  ptr2 = &id ; // if assignment is done later
  return 0;

Accessing data from pointers

* operator is used to dereference a pointer


int main()
    int id=5;
    int *ptr = id ; // if assignment is done on variable definition line

    printf("%d %d\n",id, *ptr); // id and *ptr will print the same value 5.

    return 0;
← Previous Next →