x

C++ pointers

PREV     NEXT

What are Pointers?

  • Pointers are one of the best features of C++ in comparison to other programming languages like Java, Python etc. It is a variable whose value is the address for another variable.                                                                                      Pointer                           Variable
  • We need to declare the variable as a pointer if we want to use pointers with variable.

Syntax for declaring the variable as a pointer:

  • In the above syntax, the datatype can be int, char, double, etc and the variable name is the variable declared by you. The datatype is the pointer base type and it should be a valid type. To declare the pointer we use asterisk (*).

Some of the examples of declaring pointers:

  1.                  int *marks;
  2.                  char *name;
  3.                  double *salary;

Where we use Pointers?

Pointer is very important feature in C++.


Some of the usage of pointes in C++ is:

  • The pointers can be used in arrays, functions and structures. By using the pointers in this we can reduce the code and it improves the performance.
  • By using pointers, you can dynamically allocate the memory by using malloc( ) and calloc( ) functions.

Advantages of Pointers

Some of the advantages of Pointers are:


  • The pointer allows you to access any memory location.
  • It reduces the code and improves the performance.
  • It used to retrieve the strings, trees and is used with arrays, structures and functions.
  • By using pointers, you can return multiple values from function.

Operators used in Pointers

In C++, the pointers use two operators. Before you see how pointers are declared let us discuss briefly about them.

  • Dereference Operator(*)
  • Address-of Operator(&)

Dereference Operator :

The dereference operator represents an asterisk symbol which is used to store the address of another variable.

Address-of Operator :

The address-of operator allows you to see the address of a variable.

How to declare a Pointer?

  • Pointers are used to refer directly to the value it points to. It has different properties on the basis of the pointer points to different data types like when it points to char, int or float.
  • And once it is dereferences the type of the pointer should be know so, in that case the declaration of the pointer includes the data type of the pointer which it is going to point.

Syntax of declaration of pointer:

                                       data type *variable_name;

Let us have a look at the example:

PREV     NEXT



Like it? Please Spread the word!