Application of Pointer in C++
Last Updated :
17 Jan, 2024
A pointer is a variable that stores the memory address as its value. It points to the location in the computer’s memory where the actual data is stored. Pointer is one of the core features of the C++ programming language which enables various functions like dynamic memory allocation, pass-by-reference, etc.
In this article, we will look at some major applications of pointers in C++.
Syntax of Pointers
We can simply declare a pointer of any type by using a * as a prefix as shown:
dataType *pointerName = &variableName;
To Know more refer to C++ Pointers
Application Of Pointer in C++
Pointers are one of the most powerful tools of the C++ programming language. They are used for a wide number of purposes some of which are given below:
1. Passing Arguments by Reference
Pointers in C++ are commonly used to pass arguments by reference to functions. By passing the variables by reference we can modify the actual value of the variable passed to the function, rather than working with a copy of the value.
Example
The below example demonstrates the use of a pointer to change the local values of one function in another.
C++
#include <iostream>
using namespace std;
void modifyValue( int * ptr)
{
(*ptr) += 5;
}
int main()
{
int x = 10;
cout << "Original value is: " << x << endl;
modifyValue(&x);
cout << "Modified value is: " << x << endl;
return 0;
}
|
Output
Original value is: 10
Modified value is: 15
2. For Dynamic Memory Allocation
In C++, dynamic memory allocation is very important application of pointer that allows programs to request and manage memory during runtime. The new keyword is used to allocate the dynamic memory, and it returns a pointer to allocate memory. To deallocate memory, the delete keyword is used with pointers pointing to dynamically allocated memory.
Example
The below example illustrates the use of pointers in dynamic memory allocation.
C++
#include <iostream>
using namespace std;
int main()
{
int * Int = new int ;
*Int = 42;
cout << "Value stored in dynamically allocated memory: "
<< *Int << endl;
delete Int;
int * Arr = new int [5];
for ( int i = 0; i < 5; ++i) {
Arr[i] = i + 1;
}
cout
<< "Values stored in dynamically allocated array: " ;
for ( int i = 0; i < 5; ++i) {
cout << Arr[i] << " " ;
}
cout << endl;
delete [] Arr;
return 0;
}
|
Output
Value stored in dynamically allocated memory: 42
Values stored in dynamically allocated array: 1 2 3 4 5
3. To Access Array Elements
The way there can be an array of integers or an array of floats, similarly there can be an array of pointers. Since a pointer variable always contains an address, an array of pointers would be nothing but a collection of addresses. The addresses present in the array of pointers can be addresses of isolated variables addresses of array elements or any other addresses that can be used to access array elements to print or perform operations on them. Internally the compiler uses pointers to access array elements.
Example
The below example demonstrates that the compiler internally uses pointer arithmetic to access array elements.
C++
#include <iostream>
using namespace std;
int main()
{
int arr[5] = { 1, 2, 3, 4, 5 };
int * ptr = arr;
cout << "Value at arr[0]: " << *ptr << endl;
for ( int i = 1; i < 5; ++i) {
cout << "Value at arr[" << i << "]: " << *(ptr + i)
<< endl;
}
return 0;
}
|
Output
Value at arr[0]: 1
Value at arr[1]: 2
Value at arr[2]: 3
Value at arr[3]: 4
Value at arr[4]: 5
4. To Return Multiple Values
Pointers in C++ are used to return multiple values from a function. We can achieve this by passing memory addresses (or pointers) to the function, and then the modification of values can be done by the function at those addresses.
Example
C++
#include <iostream>
using namespace std;
void getValues( int x, int y, int * sum, int * prod)
{
*sum = x + y;
*prod = x * y;
}
int main()
{
int resSum, resProd;
getValues(3, 4, &resSum, &resProd);
cout << "Sum is: " << resSum << endl;
cout << "Product is: " << resProd << endl;
return 0;
}
|
Output
Sum is: 7
Product is: 12
5. Creating Different Data Structures
Different data structures from arrays and linked lists to graphs and trees are implemented using pointers in C++. The following example demonstrates how to implement linked lists using pointers
Example
The below example demonstrates the use of pointer to dynamically allocate memory for structure.
C++
#include <iostream>
using namespace std;
class Node {
public :
int data;
Node* next;
Node()
{
data = 0;
next = NULL;
}
Node( int data)
{
this ->data = data;
this ->next = NULL;
}
};
class LinkedList {
Node* head;
public :
LinkedList() { head = NULL; }
void insertNode( int data)
{
Node* newNode = new Node(data);
if (head == NULL) {
head = newNode;
return ;
}
Node* temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
void printList()
{
Node* temp = head;
if (head == NULL) {
cout << "List empty" << endl;
return ;
}
while (temp != NULL) {
cout << temp->data << " " ;
temp = temp->next;
}
}
};
int main()
{
LinkedList list;
list.insertNode(1);
list.insertNode(2);
list.insertNode(3);
list.insertNode(4);
cout << "Elements of the list are: " ;
list.printList();
cout << endl;
return 0;
}
|
Output
Elements of the list are: 1 2 3 4
6. Achieving Runtime Polymorphism
Function pointers are used to achieve runtime polymorphism in C++. We generally create a pointer to the base class and based on the object it is pointing to, it finds the function to be executed. Not only that, pointers are used by the compiler to keep the track of virtual functions in the class.
Example
The below example demonstrates the use of function pointers.
C++
#include <iostream>
using namespace std;
class Base {
public :
virtual void display() { cout << "Base display\n" ; }
void print() { cout << "Base print\n" ; }
};
class Child : public Base {
public :
void display() override { cout << "Child display\n" ; }
void print() { cout << "Child print\n" ; }
};
int main()
{
Base* basePtr;
Child childObj;
basePtr = &childObj;
basePtr->display();
basePtr->print();
}
|
Output
Child display
Base print
Conclusion
In conclusion, pointers play an important role in C++. It offers various advantages like performance enhancement, reduced repetition, and an increase in flexibility to handle data structures. But with pros come cons so it’s important to use pointers carefully to avoid potential pitfalls like memory leaks and undefined behavior.
Share your thoughts in the comments
Please Login to comment...