Pointers are a powerful feature in C++ that allow you to manipulate memory directly. A pointer is a variable that holds the memory address of another variable.
To declare a pointer, specify the type of the variable it points to, followed by an asterisk (*) and the pointer name. You can initialize a pointer by assigning it the address of a variable using the address-of operator (&):
#include
using namespace std;
int main() {
int var = 10;
int *ptr = &var;
cout << "Value of var: " << var << endl;
cout << "Address of var: " << &var << endl;
cout << "Value of ptr (address of var): " << ptr << endl;
cout << "Value at the address stored in ptr: " << *ptr << endl;
return 0;
}
Pointers use two main operators:
A pointer that is not assigned any memory address is called a null pointer. A null pointer points
to nothing and can be created by assigning the constant NULL
or
nullptr
to the pointer:
#include
using namespace std;
int main() {
int *ptr = nullptr;
if (ptr == nullptr) {
cout << "Pointer is null" << endl;
}
return 0;
}
Pointers can be used to access elements of an array. The name of an array acts as a pointer to its first element. You can use pointer arithmetic to traverse the array:
#include
using namespace std;
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int *ptr = arr;
for (int i = 0; i < 5; ++i) {
cout << "Element " << i << ": " << *(ptr + i) << endl;
}
return 0;
}
C++ allows you to create pointers to pointers, which means a pointer that stores the address of another pointer:
#include
using namespace std;
int main() {
int var = 10;
int *ptr = &var;
int **ptr2 = &ptr;
cout << "Value of var: " << var << endl;
cout << "Address of var: " << &var << endl;
cout << "Value of ptr: " << ptr << endl;
cout << "Address of ptr: " << &ptr << endl;
cout << "Value of ptr2: " << ptr2 << endl;
cout << "Value at the address stored in ptr2: " << *ptr2 << endl;
cout << "Value at the address stored in the pointer pointed to by ptr2: " << **ptr2 << endl;
return 0;
}
Pointers can also be used to point to functions. Function pointers can be useful for implementing callback functions or for passing functions as arguments to other functions:
#include
using namespace std;
void displayMessage() {
cout << "Hello, World!" << endl;
}
int main() {
void (*funcPtr)() = displayMessage;
funcPtr();
return 0;
}
new
operator to dynamically allocate memory for
an integer.delete
operator.new
operator to dynamically allocate memory for
an array of integers.nullptr
.nullptr
before dereferencing it.nullptr
, dereference it to print
its value; otherwise, display an error message.delete
.