Pointers in C++
Pointers in C++
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 *.
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
#include <iostream>
using namespace std;
int main() {
int var = 20; // Actual variable declaration
int *ptr; // Pointer declaration
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