Example 2: Use Pointers to dynamically allocate Memory

Pointers are a powerful feature in C++ that allow direct access to memory locations. A pointer holds the memory address of another variable, enabling indirect access and modification of that variable’s value. Understanding pointers is crucial for efficient memory management, especially in dynamic memory allocation and for working with arrays or large data structures.

This example demonstrates how to use pointers to dynamically allocate memory for an array, initialize the array values, and access them using pointers.


Code Example

#include <iostream>

int main() {
    int size = 5;  // Size of the array
    int* ptr = new int[size];  // Dynamically allocate memory for an array of integers

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

    // Print the values using pointer dereferencing
    std::cout << "Array values using pointers: ";
    for (int i = 0; i < size; i++) {
        std::cout << *(ptr + i) << " ";  // Dereference pointer to access each element
    }
    std::cout << std::endl;

    // Free the dynamically allocated memory
    delete[] ptr;

    return 0;
}

Explanation & Output

Code Breakdown:

  1. Dynamically Allocating Memory:
    • int* ptr = new int[size]; → Dynamically allocates an array of size integers on the heap. The pointer ptr stores the base address of this allocated memory.
  2. Initializing Array Values Using Pointer Arithmetic:
    • In the for loop:
      • *(ptr + i) = (i + 1) * 10; → Uses pointer arithmetic (ptr + i) to access the i-th element and assigns values 10, 20, 30, 40, 50. The dereference operator (*) is used to assign values at the calculated memory address.
  3. Printing Values Using Pointers:
    • *(ptr + i) dereferences the pointer to access and print each element of the array. This is an alternative to using array indexing (ptr[i]).
  4. Memory Deallocation:
    • delete[] ptr; → Frees the dynamically allocated memory to avoid memory leaks.

Expected Output:

Array values using pointers: 10 20 30 40 50