Pointers in C++

Pointers in C++ 

Hello, Guys welcome back to another and very important article in C++ Basics Called Pointers. Most of the programmers found this topic difficult and confusing. So, in this article, I will try to explain most of the concepts in layman terms rather than more technical terms. Please read our previous article where we discussed Arrays in C++. At the end of this article, you will understand the following pointers.

  1. What is a pointer?
  2. Why we need a pointer?
  3. What is pointer dereferencing and how to do pointer dereferencing?
  4. Dynamic memory Allocation using Pointer
  5. What are the problems we usually face while using pointers?
  6. Pointer Arithmetic
What is a Pointer?

If I directly give the definition of pointer trust me you won’t get it. So, let’s directly take an example and discuss what exactly a pointer is?

int x=10; Here x is a variable that holds the value 10. But in memory 10 is stored as

What is a Pointer in C++?

The above example is a normal variable. The pointer variable is as follows.

int *ptr=&x;

What is a Pointer?

So, if you ask me to define pointer. then I would define pointer as follows. Pointers are variables that store the address of other variables where value resides.

Declaration of Pointer Variables in C++:

Pointer declaration is similar to the variable declaration but to distinguish pointer variable from normal variable we need to use ‘*’ asterisk while declaring a pointer variable.

General Syntax: <Datatype> *var_name;
Examples:
int *ptr_int; //pointer-to-integer
char *ptr_char; //pointer-to-character
bool *ptr_bool; //pointer-to-boolean

Initialization of Pointers in C++:

We can initialize the pointer at the time of declaration and we can initialize the pointer after declaration I will show you how to do it.

Example:
int x=10;
int *ptr_int = &x; //initialization at the time of declaration of pointer

int x=10;
int *ptr_int;
ptr=&x; //initialization after declaration.

Note: while initialization of pointer after declaration we should not use ‘*’ asterisk along with pointer_variable_name;

Commonly for normal variables we just do declaration and thereafter initialization same thing we did it for pointers and even you don’t see any difference in that except the use of asterisk ‘*’. But for pointers, there is another important thing we usually do i.e. dereference the pointer.

What is pointer dereferencing and how to do pointer dereferencing?

Again, if directly give the definition it is not easy to understand so let’s directly dive into an example

Example:
int x=10;
int *ptr=&x;

What is pointer dereferencing and how to do pointer dereferencing?

The same example I have taken which I used previously. Now I want to access a value 10 from ptr how I can access it? Can you Think????

Yes, I know ptr knows the address of x means currently ptr is referring to x. If I somehow think is their way to get value from the address means if I know how to defer it then I could get the value 10. Let’s say x has the address 100.ptr has a value 100 which is the address of the variable x where 10 is stored;

What is pointer dereferencing and how to do pointer dereferencing?

If I print &x then I will get the value 100
If I print ptr then I will get the value it is holding means 100
If I print just &ptr then I will get the address ptr as it is also variable let’s say its address is 110.

But now I need to print value 10 from ptr. Is it possible?

Yes, it is possible through pointer dereferencing. To defer the pointer, we need to use the asterisk ‘*’. This means if I print *ptr then I will get value 10.

How????

‘*’ associated with ptr tell the compiler to fetch the value associated with the stored address. Here stored address in ptr is 100 and the use of * tell the compiler to fetch the value associated with address 100 and the value associated with it is 10.

Let’s see how this works in the sample program:
#include<iostream>
using namespace std;
int main() {
   int x=10;
   int *ptr=&x;
   cout<<"&x print the address of x\t"<<&x<<endl;
   cout<<"ptr prints the address of variable x\t"<<ptr<<endl;
   cout<<"&ptr print the address of ptr\t"<<&ptr<<endl;
   cout<<"*ptr dereferencing happens and print the value associated with x here\t"<<*ptr<<endl;
   cout<<"x prints the value x is holding here\t"<<endl;	
   return 0;
}

Output:

Pointers Examples in C++

Note: Now if I define dereferencing. It is a way to access or manipulate data associated with the memory location pointed by a pointer. Dereferencing can be done using * along with the pointer variable name.

Now I know there is a big question in your mind about why I need a pointer and why I need to do pointer dereferencing and other complicated tasks when I know the variable value directly. And it is easy for me to print

int x=10;
cout<<x<<endl
Instead of Preforming this
int x=10;
int *ptr=&x;
cout<<*ptr<<endl;

Why perform this cycle operation when I can directly access the value?

Yes, it is a very good question and only through this question, you can understand the need is the real importance of pointers.

Why do we need Pointers in C++?

To explain the need for pointers it is necessary to go back to our basic memory layout.

Why do we need pointers?

Whenever we execute a program, program instruction will reside in the code section. And all the methods and data will reside in the stack. And code section will have only access to the stack section but it won’t have direct access to the Heap section.

Pointers in C++

Note: since the code section doesn’t have direct access to the heap section, so, we can’t use the heap memory directly and it will be got wasted, and what if stack memory got overflow? Yes, it is not a good idea to make largely available memory i.e. heap memory. Unused only because code section can’t access heap memory.

Then how to solve this problem????

Yes…………….!

You guessed it right using pointers we can solve this problem. Pointers give indirect access to heap memory for the code section. Do you want to know how pointer can give indirect access to the code section?

The solution is very simple: We know the code section can access the stack section. So, create a pointer in the stack section which pointer to the memory address of the heap section which gives indirect access to the heap section. For better understanding please have a look at the following diagram.

Important use of pointers

Indirect Access to the code section using the pointer. This is just one example of the importance of pointers in C/C++. But its importance is not only limited to accessing the heap section.

The Other important use of pointers is as follows:

  1. Suppose if your program wants to access files residing in secondary storage then it is not directly possible to access it. but using file pointers you can access the file for your program which allows you to access it.
  2. Suppose if your program wants to access network resources then only using pointers you can access it.
  3. In fact, to allow your program to access the keyboard, the monitor pointer is needed. example: To display HelloWorld in your program you will use cout in C++ which internally implements a pointer to access the console.

Now you know why we need pointers. Let’s discuss one use case of pointers which I explained gaining access to heap memory using pointers with code.

Dynamic Memory Allocation in C++ using Pointers:

Allocating memory in the heap section is happening at runtime, not at the compile-time, and hence Allocating a heap memory is called Dynamic memory Allocation.

Let’s see how to do it. Generally, we won’t allocate a single memory in the heap as you already know the complexity or circus we usually do when we use pointers. So only to allocate a block of memory we are going to use heap memory means generally for arrays we usually do dynamic memory allocation.

int array[10]; //get allocating in the stack; but to allocate in heap we need to use ‘new’ operator;

int *ptr= new int(10); this will allocate memory in heap. new int(10); allocated memory in the heap

Dynamic Memory Allocation in C++ using Pointers

Note: memory allocated in the stack is automatically deallocated once the variable out of scope but the same is not true for memory allocated in the heap. We need to explicitly deallocate memory using the delete operator in C++. For the above Example:

delete []ptr;
ptr=null;

Example Program to Illustrate Dynamic Memory Allocation:
#include<iostream>
using namespace std;
int main() { 
   int *ptr=new int(10);
   for(int i=0;i<10;++i){
         *(ptr+i)=i;
   }
    for(int i=0;i<10;++i){
      cout<<*(ptr+i)<<endl;
   }
  delete []ptr;
  *ptr=NULL;
  return 0;
}

Output:

Program to Illustrate Dynamic Memory Allocation in C++

What are the problems we usually face while using pointers?

Problem1: We already know we need to explicitly deallocate a memory but what if we forgot to deallocate. Yes, if we forgot to deallocate a memory then it will lead to a memory leak. Let’s see how?

What are the problems we usually face while using pointers?

Continues Memory leak will cause the program to crash

Problem no2: Pointer Un-initialization results in a runtime error.
#include<iostream>
using namespace std;
int main() {
   int *ptr;
   cout<<*ptr;
   return 0;
}

Output:

Pointer Un-initialization results in a runtime error

Avoid using the uninitialized pointer.

Problem no3: Dangling Pointer

Let’s explain the concept. If two pointers point to the same memory location and pointer 1 deallocate the memory but pointer 2 trying to access the memory thinking it is available is called dangling pointer.

Dangling Pointer in C++

Program to illustrate Dangling pointer:
#include<iostream>
using namespace std;
int main() {
   int *ptr1=new int(10);
   int *ptr2=ptr1;
   delete []ptr2;
   cout<<*ptr1;
   return 0;
}

Here ptr1 is a dangling pointer.

Output:

What are the problems we usually face while using pointers?

Pointer Arithmetic in C++

As we already discuss pointers are also a type of variable but instead of value, it stores address. So similar to operations performed on variables, pointers also support 4 arithmetic operations.

  1. Pointer increment.
  2. Pointer decrement.
  3. Pointer addition by constant.
  4. Pointer subtraction by constant.
  5. Difference between two pointers to calculate the distance between the pointers.

Note: Pointer multiplication, division, and modulo are not allowed. I will explain all the operation by taking one example:

Let’s take an array
Int array[5]={1,2,3,4,5}
Int *ptr=array; //ptr is pointing to the first element of an array

Pointer Arithmetic in C++

Pointer increment in C++:

int array[5]={1,2,3,4,5}
int *ptr=array;
ptr++; //pointer increment won’t add 1 to address instead it moves to the next immediate index.

Pointer increment in C++

Pointer Decrement in C++:

int array[5]={1,2,3,4,5}
int *ptr=array;
ptr++;
ptr–;

Pointer Decrement in C++

Note: pointer decrement wont decrement value 1 from address instead it moves to the previous index

Pointer Addition by Constant:

int array[5]={1,2,3,4,5}
int *ptr=array;
ptr++;
ptr–;
ptr=ptr+3; //moves the index by 3 and hence now it is pointing to value 4

Pointer Addition by Constant

Pointer Subtraction by Constant:

int array[5]={1,2,3,4,5}
int *ptr=array;
ptr++;
ptr–;
ptr=ptr+3;
ptr=ptr-2; //Decrement the index position by 2

Pointer Subtraction by Constant

Pointer Distance Between Two Pointers

Let’s say I have created another pointer which is pointing to the first element of the array to calculate the distance between two pointer we perform following operation.

int array[5]={1,2,3,4,5}
int *ptr=array;
ptr++;
ptr–;
ptr=ptr+3;
ptr=ptr-2
int *ptr1=array;
int distance=ptr-ptr1;

Pointer Distance Between Two Pointers

Program to Illustrate Pointer Arithmetic:
#include<iostream>
using namespace std;
int main() {
    int array[5]={1,2,3,4,5};
    int *ptr=array;
    cout<<"*ptr is pointing to the value \t"<<*ptr<<endl;
    ptr++;
    cout<<"After pointer increment *ptr is pointing to the value \t"<<*ptr<<endl;
 ptr--;
 cout<<"After pointer decrement *ptr is pointing to the value \t"<<*ptr<<endl;
 ptr=ptr+3;
 cout<<"After pointer Addition by constant *ptr is pointing to the value \t"<<*ptr<<endl;
    ptr=ptr-2;
 cout<<"After pointer subtraction by constant *ptr is pointing to the value \t"<<*ptr<<endl;
 int *ptr1=array;
 int distance=ptr-ptr1;
 cout<<"distance between two pointer is \t"<<distance<<endl;
  return 0;
}

Output:

Program to Illustrate Pointer Arithmetic

Assignment:

Using pointer Introduce/create crash in your program.

Here in this article, I try to explain Pointers in C++ with examples. I hope you enjoy this Pointers in C++ with Examples article.

Leave a Reply

Your email address will not be published. Required fields are marked *