Mastering C++ Pointers and Dynamic Memory with Example Code - Biz Tech

Mastering C++ Pointers and Dynamic Memory with Example Code

Listen
  #include <iostream>

int main() {
    // Declare a pointer to int
    int *ptr = nullptr;

    // Allocate memory for an int and assign its address to the pointer
    ptr = new int;

    // Assign a value to the int pointed by the pointer
    *ptr = 42;

    // Output the value and address
    std::cout << "Value: " << *ptr << " at address: " << ptr << std::endl;

    // Deallocate the memory
    delete ptr;
    ptr = nullptr;

    // Allocate memory for an array of ints
    int size = 5;
    int *arr = new int[size];

    // Assign values to the elements in the array
    for (int i = 0; i < size; i++) {
        arr[i] = i * 10;
    }

    // Output the values and addresses
    for (int i = 0; i < size; i++) {
        std::cout << "Value: " << arr[i] << " at address: " << &arr[i] << std::endl;
    }

    // Deallocate the memory
    delete[] arr;
    arr = nullptr;

    return 0;
}

This example demonstrates the following concepts in C++:

  1. Pointers: Variables that store the address of another variable (e.g., int *ptr). The * operator is used to dereference the pointer and access the value it points to.

  2. Dynamic memory allocation: Using new and delete to allocate and deallocate memory. In this example, we allocate memory for a single int and an array of ints.

  3. Pointer arithmetic: In the example, we use array notation (e.g., arr[i]) to access the elements of the dynamically allocated array. This is equivalent to using pointer arithmetic (*(arr + i)).

  4. Properly deallocating memory: It’s essential to deallocate memory using delete for single variables or delete[] for arrays when they are no longer needed. We also set the pointers to nullptr to avoid dangling pointers.