Pointers
Pointers
A pointer in C++ is a variable that stores the memory address of another variable. Instead of
holding a data value directly, it holds the location in memory where the data is stored.
Why Pointers?
Pointer Syntax:
A pointer can be declared in the same way as any other variable but with an asterisk
symbol (*) as shown:
data_type* pointer_name;
* → declares a pointer.
& → retrieves the memory address (address-of operator).
* (again) → dereferences a pointer (access the value it points to).
#include <iostream>
int main() {
cout << "Pointer holds address: " << ptr << endl;
return 0;
}
Output:
Value of num: 42
Address of num: 0x61fefc
Pointer holds address: 0x61fefc
Value at pointer: 42
Explanation:
Term Description
int num = 42; Declares an integer variable num
int* ptr = # Declares a pointer that stores the address of num
*ptr Dereferences the pointer to get the value 42
void update(int* p)
{
*p = *p + 5;
}
Conclusion:
A pointer is a powerful feature in C++ used to access and manipulate memory directly. It
forms the basis for many advanced programming techniques and is essential for efficient system-
level development.
In C++, you can pass a pointer to a function so that the function can modify the original
variable from the caller.
#include <iostream>
int main() {
cout << "Before function call: " << num << endl;
cout << "After function call: " << num << endl;
return 0; }
Output:
Code Description
Let’s compare both approaches: pass by pointer (reference) vs pass by value using the same
example:
int main() {
Output:
20
The original variable num remains unchanged because only a copy of num was passed.
Summary
Method Function Declaration Original Value Changed?
Conclusion:
When passing by value, the function works on a copy of the variable — changes are local and
not reflected outside the function.
When passing by pointer (or reference), the function works on the original variable —
changes are visible outside the function.