Overview:

In this blog, we will go through the basics of pointers. And will try to demystify the scary-looking syntax of the pointer.

How variables are stored in memory?

To understand pointers we first need to understand how a variable is stored in a memory. Every time we create a variable it gets some memory (The size of memory depends on the data type of the variable and compiler), it has an address where it resides in the memory and it has a value that we initialize or assign to it.

See the below code snippet to understand it more clearly.

int num = 10;

Here, we are declaring a variable called num, which is of type int and 10 is the value that is stored in it. Visually you can think of it as below:

Screenshot (307).png

Did you notice the numbering on the left side? Those are the addresses. And our variable is taking four bytes from 502 to 505. Why four bytes? Remember it depends on the data type we are using, here it is int and in C/C++ an int usually takes four bytes of memory. Does that mean our variable num has four addresses? num takes four bytes in memory but in C/C++ we refer to it by its first address only. So, if someone asks us what is the address of num? We will simply say 502.

Now, Since we are familiar with how a variable is stored in memory let's see our definition of the pointer.

What are pointers?

"Pointer is a variable that stores the address of another variable of the same type."

In simple words, we can say pointers are also variables but they are special kinds of variables because they only store the address of another variable. But it comes with a condition that an int type pointer can only store the address of an int variable and a char type pointer can store an address of only a char variable and similarly for other datatypes. Hence, the pointer stores the address of another variable of the same type.

Declaring and initializing pointers in C/C++ :

A pointer is declared just like another variable the only difference being its name is preceded by an asterisk(). Technically '' is an operator in C/C++ which is called dereferencing operator. So a pointer is declared with the help of dereferencing operator.

int num = 10; //Declaring and initializing normal variable in c/ c++
int *ptr; //Declaring pointer in c/c++

Initializing pointer variables :

To understand the initialization of a pointer variable we first need to understand the address operator in C/C++. Address operator is denoted by an ampersand sign '&'. It returns the memory address of the variable with which it is used. So, if we want to print the memory address of the num variable that we created above. We will simply type:

cout<< &num; //It will print address of num

Now, Let's look at how a pointer is initialized. Look at the code snippet below: