Example 3: Dereference Operator and Dynamic Memory Allocation

In more advanced C++ applications, the dereference operator (*) is frequently used in dynamic memory allocation, function arguments (pass-by-pointer), and handling complex data structures like arrays and linked lists. This example demonstrates the use of the dereference operator in dynamic memory allocation and pointer arithmetic to manipulate an array stored in the heap.


Advanced Code Example

#include <iostream>

int main() {
    // Dynamically allocate an array of 5 integers
    int* arr = new int[5];

    // Initialize values using pointer arithmetic
    for (int i = 0; i < 5; i++) {
        *(arr + i) = (i + 1) * 10;  // Assign values: 10, 20, 30, 40, 50
    }

    // Display values using pointer dereferencing
    std::cout << "Array values using pointer dereferencing: ";
    for (int i = 0; i < 5; i++) {
        std::cout << *(arr + i) << " ";  // Dereference to access values
    }
    std::cout << std::endl;

    // Modify values using pointer arithmetic
    for (int i = 0; i < 5; i++) {
        *(arr + i) += 5;  // Increment each value by 5
    }

    // Display modified values
    std::cout << "Modified array values: ";
    for (int i = 0; i < 5; i++) {
        std::cout << *(arr + i) << " ";
    }
    std::cout << std::endl;

    // Free allocated memory
    delete[] arr;

    return 0;
}

Explanation & Output

Code Breakdown:

  1. Dynamic Memory Allocation:
    • int* arr = new int[5]; → Allocates an integer array of size 5 in the heap.
    • arr stores the base address of this allocated memory.
  2. Initializing Values with Pointer Arithmetic:
    • *(arr + i) = (i + 1) * 10; assigns values 10, 20, 30, 40, 50 to the array.
    • Here, arr + i moves the pointer to the i-th index, and * accesses/modifies the value.
  3. Reading Values via Dereferencing:
    • std::cout << *(arr + i); retrieves values from the dynamically allocated array.
  4. Modifying Values Using Pointers:
    • *(arr + i) += 5; increases each element by 5.
    • This demonstrates modifying array elements directly via pointers.
  5. Freeing Memory:
    • delete[] arr; ensures proper memory management by deallocating the allocated memory.

Expected Output:

Array values using pointer dereferencing: 10 20 30 40 50 
Modified array values: 15 25 35 45 55 

This example highlights dynamic memory allocation, pointer arithmetic, and memory management, showing how the dereference operator (*) is crucial in managing and manipulating dynamically allocated data in C++.