Open In App

Application of Pointer in C++

Last Updated : 17 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ program to demonstrate the use of pointer to change
// local values of one function in another.
  
#include <iostream>
using namespace std;
  
// Function to modify the value of an integer using a
// pointer
void modifyValue(int* ptr)
{
    // Dereferencing the pointer to access and modify the
    // actual value
    (*ptr) += 5;
}
  
int main()
{
    // Declaring and initializing an integer variable
    int x = 10;
  
    // Displaying the original value
    cout << "Original value is: " << x << endl;
  
    // Passing the address of the variable to the function
    modifyValue(&x);
  
    // Displaying the modified value
    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()
{
    // Dynamic memory allocation for an integer
    int* Int = new int;
  
    // Store a value in the dynamically allocated memory
    *Int = 42;
  
    // Display the value stored in the dynamically allocated
    // memory
    cout << "Value stored in dynamically allocated memory: "
         << *Int << endl;
  
    // Deallocate the dynamically allocated memory to avoid
    // memory leaks
    delete Int;
  
    // Dynamic memory allocation for an array of integers
    int* Arr = new int[5];
  
    // Store values in the dynamically allocated array
    for (int i = 0; i < 5; ++i) {
        Arr[i] = i + 1;
    }
  
    // Display the values stored in the dynamically
    // allocated array
    cout
        << "Values stored in dynamically allocated array: ";
    for (int i = 0; i < 5; ++i) {
        cout << Arr[i] << " ";
    }
    cout << endl;
  
    // Deallocate the dynamically allocated array
    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++




//// C++ program to demonstrate that compiler
// internally uses pointer arithmetic to access
// array elements.
  
#include <iostream>
using namespace std;
int main()
{
    // Declare an array of integers
    int arr[5] = { 1, 2, 3, 4, 5 };
  
    // Declare a pointer and point it to the first element
    // of the array
    int* ptr = arr;
  
    // Access array elements using pointers
    cout << "Value at arr[0]: " << *ptr << endl;
  
    // Using pointer to access other elements
    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++




// C++ program to return multiple values from function using
// pointers
  
#include <iostream>
using namespace std;
  
// Function that returns multiple values using pointers
void getValues(int x, int y, int* sum, int* prod)
{
    // Calculating sum and product and storing them at the
    // provided addresses
    *sum = x + y;
    *prod = x * y;
}
  
int main()
{
    // Declaring the variables to store the results
    int resSum, resProd;
  
    // Calling the function and passing addresses of
    // variables to store results
    getValues(3, 4, &resSum, &resProd);
  
    // Displayinf the results
    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++




// C++ program to demonstrate linked list operations
#include <iostream>
using namespace std;
  
// Node class to represent a node of the linked list.
class Node {
public:
    int data;
    Node* next;
  
    // Default constructor
    Node()
    {
        data = 0;
        next = NULL;
    }
  
    // Parameterised Constructor
    Node(int data)
    {
        this->data = data;
        this->next = NULL;
    }
};
  
// LinkedList class to implement a linked list.
class LinkedList {
    Node* head;
  
public:
    // Default constructor
    LinkedList() { head = NULL; }
  
    // Function to insert a node at the end of the linked
    // list.
    void insertNode(int data)
    {
        // Create the new Node.
        Node* newNode = new Node(data);
  
        // If list is empty, assign newNode to head
        if (head == NULL) {
            head = newNode;
            return;
        }
  
        // Traverse till end of list
        Node* temp = head;
        while (temp->next != NULL) {
            // Move to next node
            temp = temp->next;
        }
  
        // Insert newNode at the end.
        temp->next = newNode;
    }
  
    // Function to print the linked list.
    void printList()
    {
        Node* temp = head;
  
        // Check for empty list.
        if (head == NULL) {
            cout << "List empty" << endl;
            return;
        }
  
        // Traverse the list and print each node's data.
        while (temp != NULL) {
            cout << temp->data << " ";
            temp = temp->next;
        }
    }
};
  
// Driver Code
int main()
{
    LinkedList list;
  
    // Inserting nodes
    list.insertNode(1);
    list.insertNode(2);
    list.insertNode(3);
    list.insertNode(4);
  
    cout << "Elements of the list are: ";
  
    // Print the list
    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++




// C++ Program to demonstrate the Virtual Function
#include <iostream>
using namespace std;
  
// Base class
class Base {
public:
    // virtual function
    virtual void display() { cout << "Base display\n"; }
  
    void print() { cout << "Base print\n"; }
};
  
// Child class
class Child : public Base {
public:
    void display() override { cout << "Child display\n"; }
  
    void print() { cout << "Child print\n"; }
};
  
// Driver code
int main()
{
    // Create a pointer of type Base
    Base* basePtr;
  
    // Point basePtr to an object of type Child
    Child childObj;
    basePtr = &childObj;
  
    // Call the virtual function
    basePtr->display();
  
    // Call the non-virtual function
    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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads