Pointers:
In C++, pointers are variables that store the memory address of another variable.
Understanding pointers and memory addresses is crucial in C++ because they provide
powerful ways to manipulate data and memory directly.
Basics of Pointers
1. Declaration: A pointer is declared by specifying the type of the variable it will point
to, followed by an asterisk *.
int *ptr; // Declares a pointer to an integer
2. Address-of Operator &: This operator returns the memory address of a variable.
int x = 10;
int *ptr = &x; // ptr now holds the address of x
3. Dereferencing Operator *: This operator accesses the value at the memory address
held by the pointer.
int y = *ptr; // y is now 10, the value stored at the address ptr is pointing to
Example of Pointer Usage
#include <iostream>
using namespace std;
int main() {
int var = 20; // Actual variable declaration
int *ptr; // Pointer declaration
ptr = &var; // Store the address of var in ptr
cout << "Value of var: " << var << endl;
cout << "Address of var: " << &var << endl;
cout << "Value stored at ptr: " << ptr << endl;
cout << "Value at the address stored in ptr: " << *ptr << endl;
return 0;
}
Output:
Value of var: 20
Address of var: 0x7ffd9b2b9164
Value stored at ptr: 0x7ffd9b2b9164
Value at the address stored in ptr: 20
Important Concepts
Null Pointer: A pointer that is not pointing to any memory location. It is initialized
with nullptr in modern C++ (or NULL in older versions).
int *ptr = nullptr;
Pointer Arithmetic: You can perform arithmetic operations on pointers to traverse
through arrays. For example, incrementing a pointer moves it to the next element in
an array.
int arr[3] = {10, 20, 30};
int *ptr = arr; // Points to the first element of the array
ptr++; // Now points to the second element
cout << *ptr; // Outputs 20
Pointers and Arrays: The name of an array acts as a pointer to its first element. For
instance, arr and &arr[0] are equivalent.
Dynamic Memory Allocation: Pointers are used for dynamic memory management
using new and delete.
int *ptr = new int; // Allocate memory for an integer
*ptr = 25; // Assign a value to the allocated memory
delete ptr; // Free the allocated memory
Address in C++
The address of a variable in memory is often represented in hexadecimal.
Knowing the address allows you to directly manipulate the data stored at that location,
which is essential for certain low-level programming tasks, such as systems
programming.