C++ Program for Reference to a Pointer

02/06/2024 0 By indiafreenotes

In C++, a reference to a pointer is essentially an alias for a pointer variable. This allows you to manipulate the pointer itself, not just the value it points to. Using references to pointers can be particularly useful in functions where you need to modify the actual pointer passed as an argument.

Example Program: Using a Reference to a Pointer

Here’s a complete program that demonstrates the use of references to pointers in C++:

#include <iostream>

using namespace std;

// Function to modify a pointer via a reference to a pointer

void modifyPointer(int*& ref) {

    ref = new int; // Allocate new memory

    *ref = 20;     // Assign a value to the allocated memory

}

int main() {

    int* ptr = nullptr; // Initialize pointer to nullptr

    cout << “Initial pointer value: ” << ptr << endl;

    // Pass the pointer to the function

    modifyPointer(ptr);

    // Output the modified pointer value and the value it points to

    cout << “Modified pointer value: ” << ptr << endl;

    cout << “Value at the modified pointer: ” << *ptr << endl;

    // Clean up dynamically allocated memory

    delete ptr;

    return 0;

}

Explanation of the Program

  1. Function ‘modifyPointer’

This function takes a reference to a pointer to an integer (‘int*& ref’). It allocates new memory and assigns the value ‘20’ to the newly allocated memory. The modifications made to ‘ref’ affect the original pointer passed to the function.

  1. Main Function

  • A pointer ‘ptr’ is initialized to ‘nullptr’.
  • The initial value of ‘ptr’ is printed (which is ‘nullptr’).
  • The pointer ‘ptr’ is passed to the ‘modifyPointer’ function by reference.
  • The function allocates memory for ‘ptr’ and assigns the value ‘20’ to it.
  • The modified pointer value and the value it points to are printed.
  • Finally, the dynamically allocated memory is deallocated using ‘delete’.

Benefits of Using References to Pointers:

  1. Efficiency

Passing references to pointers is more efficient than passing pointers by value, especially when dealing with large data structures.

  1. Direct Modification

Allows direct modification of the original pointer, making it useful in scenarios where functions need to update pointer addresses