A pointer is a variable that holds the memory address, usually a location of another variable in memory. The use of pointers is critical for the successful programming in C++.

The three reasons that support this are,

  • Pointers provide the means through which the memory location of a variable can be directly accessed and hence can be manipulated in any way.
  • Pointers support dynamic allocation routines.
  • Pointers can improve the efficiency of certain routines.

Since pointers hold memory location of another variable and also facilitate dynamic memory allocation, we must understand the memory map of a C++ program. After the compilation of program, C++ creates four logically distinct regions of memory that are used for four different functions.

  • Stack : It is used for holding the return address at function calls, arguments passed and local variable for functions; it also stores the current state of the CPU.
  • Heap : Memory area is a region of free memory from where memory is allocated for the dynamic allocation in C++.
  • Global Variable : This space is used to store the global variable used in the program.
  • Program Code : This region holds the compiled code of the program.

Dynamic and Static allocation of memory

  • Static allocation : When the amount of memory to be allocated is known before run-time i.e. memory is allocated during compile time, this is know as Static memory allocation
  • Dynamic allocation : When the amount of memory to be allocated is not know at the compile time i.e. memory is allocated at runtime, this is know as Dynamic memory allocation.

Pointers have two major operators

  • * ( called "value at address" sign)
  • & ( called "address of" sign)

Variables are stored at particular locations or addresses in memory. if v is a variable then &vis the address in memory of its stored value. Pointers are used to access such memory locations directly.

Declaration and Initialization of Pointers

Pointer variables are declared like normal variables but with the addition of * operator.

Example:

Here, the & operator makes iptr hold the memory address of the variable i. The second operator * does the exact opposite of this operator, as *iptr displays the value 25 and &iptr displays 1050.

Example:

This program displays the address as well as the value of variable with the help of pointers.