Back to: C++ Tutorials For Beginners and Professionals
Why Pointers in C++ with Examples:
In this article, I am going to discuss Why Pointers in C++ Language with examples. Please read our previous articles, where we discussed Pointers in C++ with examples.
Why do we need pointers in C++?
To explain the need for pointers it is necessary to go back to our basic memory layout.
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.
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.
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 the 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 that 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.
Indirect Access to code section using 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.
Other important use of pointers is as follows:
- 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.
- Suppose if your program wants to access network resources then only using pointers you can access it.
- In fact, to allow your program to access the keyboard, a 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.
In the next article, I am going to discuss Dynamic Memory Allocation in C++ with examples. Here, in this article, I try to explain Why Pointers in C++ Language with examples. I hope you enjoy this Why Pointers in C++ with examples article. I would like to have your feedback. Please post your feedback, question, or comments about this article.