Pointers are a fundamental feature in C++ that provide direct memory access and manipulation capabilities. They are powerful but can be complex and prone to errors if not used carefully. Here’s an overview of pointers, their uses, and best practices for working with them.
A pointer is a variable that stores the memory address of another variable. In C++, pointers are declared using the *
operator.
int x = 10;
int* p = &x; // p stores the address of x
int* ptr; // Declares a pointer to an int
int x = 10;
ptr = &x; // Initializes the pointer with the address of x
Dereferencing a pointer means accessing the value stored at the memory address the pointer points to.
int value = *ptr; // Dereferences ptr to get the value of x
*ptr = 20; // Changes the value of x to 20
A pointer that is not initialized to any valid memory address is called a null pointer. It’s a good practice to initialize pointers to nullptr
to avoid undefined behavior.
int* ptr = nullptr;
Pointers are used for dynamic memory allocation using new
and delete
.
int* ptr = new int; // Allocates memory for an int
*ptr = 5;
delete ptr; // Frees the allocated memory
int* arr = new int[10]; // Allocates memory for an array of 10 ints
delete[] arr; // Frees the allocated array memory
Arrays and pointers are closely related. Array names can be used as pointers to the first element of the array.
int arr[5] = {1, 2, 3, 4, 5};
int* ptr = arr; // ptr points to the first element of arr
for (int i = 0; i < 5; ++i) {
std::cout << *(ptr + i) << " "; // Accesses array elements using pointer arithmetic
}