A pointer is a special variable that stores the memory address of another variable. Pointers are powerful because they allow you to directly access and manipulate memory locations.
To declare a pointer, use the *
symbol before the pointer variable name. The pointer must specify the type of data it points to.
int* ptr; // Pointer to an integer char* cptr; // Pointer to a character
Use the address-of operator &
to assign the address of a variable to a pointer.
int num = 42; int* ptr = # // ptr now holds the address of num
The dereference operator *
is used to access or modify the value stored at the memory location the pointer points to.
cout << *ptr; // Outputs: 42 *ptr = 100; // Changes num to 100 cout << num; // Outputs: 100
&
to get the address of a variable.*
to access or modify the value at the pointerβs address.#include <iostream> using namespace std; int main() { int num = 25; int* ptr = # cout << "Value of num: " << num << endl; cout << "Address of num: " << ptr << endl; cout << "Value at address stored in ptr: " << *ptr << endl; *ptr = 50; // modify value using pointer cout << "Modified value of num: " << num << endl; return 0; }
nullptr
(C++11 onwards) to indicate a pointer that points to nothing.Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!