C++ Pointer

tutorial and example
tutorial and example

Pointer is a derived data type that stores the address of variable. Pointer is used for memory management and dynamic memory allocatation. Pointer works on address of data rather than actual of data.

Pointer Declaration



Here data-type is one of the C++ data types, pointer-variable is the name of pointer and * (asterisk) refers to pointer. Asterisk (*) can be placed at three different locations as:

  1. Place immediately before pointer-variable.
  2. Place between data type and pointer variable.
  3. Place immediately after data type.


Pointer Initialization


Here ptr is a pointer variable, x is variable of int data type. &x contains the address of variable x and prt = &x; assign address of x into ptr.

Deference operator (*) and Reference operator (&)

Deference operator (*) gives the value of variable stored at memory location. Reference operator (&) gives the memory address of a variable.

For example: If a number variable is stored in the memory address 0x22, and it contains a value 10.

Dereference (*) operator gives the value 10, while reference (&) operator gives the value 0x22.

C++ Pointer Example