In this tutorial, you will Pointers in C++ with their examples. A pointer is a variable in C++ which contains the address of the different variables. The Pointer has data types just like variables. For example, an integer type pointer can contain the address of an integer variable. So, the character type pointer can contain the address of the char variable.
Introduction to Pointers in C++
Pointers are the most powerful tool in the C++ language, it helps the programmer to reach and manage the memory immediately. For instance, when a variable is created, the role of the compiler is to do memory allocation to collect the value of the variable. So, this value is retrieved using the variable name specified in the data. C++ has the compatibility to save and retrieve the data from the memory including the address of the memory location at which the data is stored. C++ also performs pointers on a pointer.
Syntax
The syntax of declaring a pointer is as follows:
Data Type *var;
- Data Type: It is the type of variable shows by the pointer variable.
- *: It indicates that the variable is a pointer variable.
- var: This is the same name of the pointer variable.
Example:
int*p;
The above statement declares a pointer variable p. The data type int indicates that it can store the memory address of an integer variable. However, The data type of a pointer must be the same as the data type of the variable whose memory address is to be stored in the pointer.
Program Example:
#include<iostream> #include<conio.h> int main() { int n; int *ptr; cout <<"Enter an interger"; cin>>n; ptr=&n; cout<<"The value of n:"<<n<<endl; cout<<"The address of n:"<<prt<<endl; getch(); }
Why do we need Pointers?
Dynamic memory allocation is performed simply in C++ using pointers. So, the various notable point of pointers is they are extremely efficient in handling the various data types. They improve the execution speed when the function returns one value and also give hand in obtaining a variable set outside the function. For Instance, The various common-mode includes data management and obtaining class member functions. pointers in C++ with examples.