In today's tutorial, I will discuss pointers in c++. Let's first know what pointer is? Pointer is a type of data type which stores the address of another data type. When we create a variable, it is stored in ram and the address where the store is in ram is the address. That is, the address of a variable is where it is stored. Here is the pointer
Why Pointer Needed?
When we work with a variable inside a function or class, they are local variables. In this case, reassigning the value of a variable does not change the value of the variable in the main function. Therefore, we pass the address of the variable to any function using pointers. I can change the value of that variable.
Now let's know about pointers in detail
Before knowing about pointers we need to know about two operators. They are:
& → address of operator
* → dereference operator
To know the address of a variable, we use the & operator. For example, if a variable is a, then its address will be &a
Now let's know about * operator. Using * operator we will declare pointer variable and again using * we will get value of original variable from pointer variable.
Now let's see some examples
First let's create a variable named x.
int x = 5;
Now let's write to store the address of x in the variable named y:
int x = 5; int* y = &x;
To create a pointer variable, the address of the variable to be stored must be given a * after the data type. For example, if int is int*, if string is string*
Now if you cout y, you can see the address of x.
cout<<y;
Output:
0x7ffeeef92794
Now to print the value of x write:
cout<<*y;
In this case, use * before the name of the pointer variable. For example, *y here
output:
5
Here, the address of x is stored in y. Now many people may ask, how to store the address of y in another pointer? So let's find out.
Earlier we used a * after the data type while creating the pointer. However, this time we have to use two *. Now if we want to store the address of y in z, we have to write:
int x = 5: int* y = &x; int** z = &y;
Now if you want to print the value of x through z then write:
cout<<**z;
That is, use ** here.
This was basically the concept of pointers in c++