Pointer

Programming

Pointers are variables that store memory addresses of other variables. They are fundamental to C++ and enable dynamic memory allocation, efficient parameter passing, and low-level memory manipulation.

Basic Usage

#include <iostream>

int main() {
    int x = 10;
    int* ptr = &x;
    std::cout << "Value of x: " << x << std::endl;
    std::cout << "Address of x: " << ptr << std::endl;
    std::cout << "Value at address: " << *ptr << std::endl;
    return 0;
}

Key Concepts

Pointer Operations

Pointers support arithmetic operations and can be used to modify values indirectly:

#include <iostream>

int main() {
    int x = 10;
    int* ptr = &x;
    
    // Modify value through pointer
    *ptr = 20;
    std::cout << "x after modification: " << x << std::endl;
    
    // Pointer arithmetic
    int arr[5] = {1, 2, 3, 4, 5};
    int* p = arr;  // Points to first element
    std::cout << "First element: " << *p << std::endl;
    std::cout << "Second element: " << *(p + 1) << std::endl;
    
    return 0;
}

Dynamic Memory Allocation

Pointers are essential for dynamic memory allocation:

#include <iostream>

int main() {
    // Allocate memory dynamically
    int* ptr = new int(42);
    std::cout << "Value: " << *ptr << std::endl;
    
    // Always deallocate to prevent memory leaks
    delete ptr;
    ptr = nullptr;  // Good practice: set to nullptr after deletion
    
    return 0;
}

Common Pitfalls

Best Practices

Pointer vs Reference

References are safer alternatives when you don't need pointer features:

Output

Value of x: 10
Address of x: 0x7fff5fbff6ac
Value at address: 10

Note: The actual memory address will vary each time the program runs.