#include <iostream>
using namespace std;
int main() {
int number = 25;
int* ptr = &number;
cout << "Value: " << number << endl;
cout << "Address: " << &number << endl;
cout << "Pointer value: " << ptr << endl;
cout << "Value through pointer: " << *ptr << endl;
return 0;
}Pointers in C++: Memory Addresses, Dereferencing, and Practical Uses
Direct Answer & Core Concept
Pointers are one of the most important concepts in C++. They allow a program to work directly with memory addresses and access data stored at those locations.
Pointers are useful for working with arrays, dynamic memory allocation, functions, data structures, and efficient memory management.
Detailed Explanation & Mechanics
1. What Is a Pointer in C++?
A pointer is a variable that stores the memory address of another variable.
Normally, a variable stores a value. A pointer stores the address where that value is located in memory.
For example:
Example output:
Value: 25
Address: 0x7ffe1234
Pointer value: 0x7ffe1234
Value through pointer: 25The memory address shown above is illustrative. Actual addresses differ between program executions and systems.
Explanation
numberstores the integer value25.&numberobtains the memory address ofnumber.ptrstores that address.*ptraccesses the value stored at that address.
A pointer provides indirect access to another variable.
2. Pointer Declaration in C++
To declare a pointer, specify the data type followed by an asterisk (*) and the pointer variable name.
Syntax
data_type* pointer_name;Examples
int* intPtr;
float* floatPtr;
double* doublePtr;
char* charPtr;Each pointer has a type that determines the type of object it can point to.
For example:
int number = 100;
int* ptr = &number;Here, ptr is an integer pointer because it points to an integer variable.
Different pointer declaration styles
All the following declarations are valid:
int* ptr1;
int *ptr2;
int * ptr3;They have the same meaning. A common style is int* ptr.
Important: When declaring multiple pointers, remember that the asterisk belongs to each declarator.
int* first, second;Here, first is a pointer, but second is a normal integer.
To declare two pointers:
int *first, *second;3. Understanding the Address-of Operator (&)
The address-of operator (&) returns the memory address of a variable.
Example
#include <iostream>
using namespace std;
int main() {
int age = 30;
cout << "Age: " << age << endl;
cout << "Memory address: " << &age << endl;
return 0;
}Example output:
Age: 30
Memory address: 0x7ffe1234The address is not fixed. It can change when the program runs again.
Using the address operator with a pointer
int age = 30;
int* ptr = &age;The expression &age gets the address of age, and that address is stored in ptr.
4. Understanding the Dereference Operator (*)
The dereference operator (*) accesses the value stored at the memory address held by a pointer.
This operation is also called indirection.
Example
#include <iostream>
using namespace std;
int main() {
int number = 50;
int* ptr = &number;
cout << *ptr << endl;
return 0;
}Output:
50Changing a variable through a pointer
You can also modify the original variable by dereferencing its pointer.
#include <iostream>
using namespace std;
int main() {
int number = 50;
int* ptr = &number;
*ptr = 100;
cout << "Number: " << number << endl;
return 0;
}Output:
Number: 100The statement *ptr = 100 changes the value of the variable whose address is stored in ptr.
Difference between & and *
| Operator | Meaning | Example |
|---|---|---|
& | Gets a variable's address | &number |
* | Declares a pointer or dereferences one | int* ptr, *ptr |
5. How to Initialize a Pointer
A pointer should be initialized before it is dereferenced.
Example
#include <iostream>
using namespace std;
int main() {
int value = 75;
int* ptr = &value;
cout << *ptr << endl;
return 0;
}Output:
75Uninitialized pointer
int* ptr;
// Do not dereference ptr here.An uninitialized pointer contains an indeterminate value. Dereferencing it can cause undefined behavior.
A safer option is to initialize a pointer to nullptr when it does not yet point to an object.
int* ptr = nullptr;6. Null Pointers in C++
A null pointer does not point to a valid object or function.
C++ provides the nullptr keyword to represent a null pointer.
Example
#include <iostream>
using namespace std;
int main() {
int* ptr = nullptr;
if (ptr == nullptr) {
cout << "Pointer is null" << endl;
}
return 0;
}Output:
Pointer is nullWhy use nullptr?
It makes the pointer's empty state clear.
It helps prevent accidental use of uninitialized pointer values.
It can be checked before accessing an object.
It is safer and clearer than using the integer literal
0.
Important: Never dereference a null pointer.
7. Pointer Arithmetic in C++
Pointer arithmetic allows certain operations on pointers, such as moving to the next or previous element of an array.
When a pointer is incremented, it advances by the size of the type it points to, not necessarily by one byte.
Example: Incrementing a pointer
#include <iostream>
using namespace std;
int main() {
int numbers[] = {10, 20, 30, 40};
int* ptr = numbers;
cout << *ptr << endl;
ptr++;
cout << *ptr << endl;
return 0;
}Output:
10
20The pointer initially points to the first array element. After ptr++, it points to the next element.
Common pointer arithmetic operations
| Operation | Meaning |
|---|---|
ptr++ | Moves to the next element |
ptr-- | Moves to the previous element |
ptr + n | Moves forward by n elements |
ptr - n | Moves backward by n elements |
ptr1 - ptr2 | Calculates the element distance between pointers into the same array |
Pointer arithmetic is only valid within the same array object or one position past its last element. The one-past position must not be dereferenced.
8. Pointers and Arrays
Pointers and arrays are closely related in C++.
In many expressions, an array name converts to a pointer to its first element. This is called array-to-pointer conversion.
Example
#include <iostream>
using namespace std;
int main() {
int numbers[] = {10, 20, 30, 40, 50};
int* ptr = numbers;
for (int i = 0; i < 5; i++) {
cout << *(ptr + i) << endl;
}
return 0;
}Output:
10
20
30
40
50Explanation
numbersconverts to a pointer to its first element in this assignment.ptrpoints tonumbers[0].ptr + ipoints to the element at indexi.*(ptr + i)reads that element.
For an array, these expressions access the same element:
numbers[i]
*(numbers + i)Important: An array and a pointer are not the same thing. An array has its own fixed size and storage, while a pointer is a separate variable that stores an address.
9. Pointer to Pointer in C++
A pointer to pointer stores the address of another pointer.
It is also called a double pointer.
Syntax
data_type** pointer_name;Example
#include <iostream>
using namespace std;
int main() {
int number = 100;
int* ptr = &number;
int** doublePtr = &ptr;
cout << "Value: " << number << endl;
cout << "Using pointer: " << *ptr << endl;
cout << "Using double pointer: " << **doublePtr << endl;
return 0;
}Output:
Value: 100
Using pointer: 100
Using double pointer: 100How does it work?
numberstores100.ptrstores the address ofnumber.doublePtrstores the address ofptr.**doublePtraccesses the original integer value.
Double pointers are useful in certain dynamic data structures and when a function needs to modify a pointer variable itself.
10. Pointers and Functions
Pointers can be passed to functions to allow a function to access or modify the original variable.
Example: Passing a pointer to a function
#include <iostream>
using namespace std;
void updateValue(int* ptr) {
if (ptr != nullptr) {
*ptr = 500;
}
}
int main() {
int number = 100;
updateValue(&number);
cout << number << endl;
return 0;
}Output:
500Explanation
&numberpasses the address of the original variable.int* ptrreceives that address.*ptr = 500modifies the original variable.The updated value is visible in
main().
For many ordinary C++ functions, references are simpler and safer when you only need to modify an existing object. Pointers are useful when an optional object or explicit address-based behavior is needed.
11. Dynamic Memory Allocation Using Pointers
C++ allows memory to be allocated dynamically while a program is running.
The new operator allocates memory, and delete releases memory allocated with new.
Example: Using new and delete
#include <iostream>
using namespace std;
int main() {
int* ptr = new int;
*ptr = 200;
cout << "Value: " << *ptr << endl;
delete ptr;
ptr = nullptr;
return 0;
}Output:
Value: 200Explanation
new intallocates memory for one integer.The returned address is stored in
ptr.*ptr = 200stores a value in the allocated memory.delete ptrreleases that memory.ptr = nullptrprevents the pointer from retaining a stale address.
Dynamic array allocation
You can also allocate an array dynamically.
#include <iostream>
using namespace std;
int main() {
int size = 3;
int* numbers = new int[size]{10, 20, 30};
for (int i = 0; i < size; i++) {
cout << numbers[i] << endl;
}
delete[] numbers;
numbers = nullptr;
return 0;
}Output:
10
20
30Use delete[] for memory allocated with new[]. Using the wrong form of delete results in undefined behavior.
Modern C++ recommendation
In modern C++, prefer standard library containers such as std::vector for dynamic arrays and smart pointers such as std::unique_ptr or std::shared_ptr for managed dynamic objects.
These tools help reduce memory leaks and ownership errors.
12. Constant Pointers and Pointers to Constants
C++ provides different ways to use const with pointers.
Pointer to a constant value
const int* ptr;You cannot modify the pointed-to value through this pointer, but you can make the pointer point somewhere else.
Constant pointer
int* const ptr = &number;The pointer cannot be made to point to another address, but the pointed-to value can be modified through it.
Constant pointer to a constant value
const int* const ptr = &number;Neither the pointer nor the pointed-to value can be modified through this pointer.
Comparison
| Declaration | Change pointer address? | Modify value through pointer? |
|---|---|---|
int* ptr | Yes | Yes |
const int* ptr | Yes | No |
int* const ptr | No | Yes |
const int* const ptr | No | No |
13. Void Pointers in C++
A void* is a pointer type that can hold the address of an object of any object type.
However, a void* cannot be directly dereferenced because it does not specify the pointed-to type.
Example
#include <iostream>
using namespace std;
int main() {
int number = 100;
void* ptr = &number;
cout << *static_cast<int*>(ptr) << endl;
return 0;
}Output:
100Here, static_cast<int*>(ptr) converts the void* back to an int* before dereferencing it.
The cast must match the actual object type. A void* is not a replacement for type-safe pointers in ordinary C++ code.
14. Function Pointers in C++
A function pointer stores the address of a function. It allows a function to be called indirectly through a pointer.
Syntax
return_type (*pointer_name)(parameter_types);Example
#include <iostream>
using namespace std;
int add(int a, int b) {
return a + b;
}
int main() {
int (*operation)(int, int) = add;
cout << operation(10, 20) << endl;
return 0;
}Output:
30Explanation
add()is a function that accepts two integers.operationis a pointer to a function with a matching signature.operation(10, 20)calls the function through the pointer.
Function pointers are useful for callbacks, selecting operations, and working with some C and C++ APIs.
15. Practical Uses of Pointers in C++
Pointers are used in many areas of C++ programming.
| Use case | How pointers help |
|---|---|
| Dynamic memory | Manage objects created during program execution |
| Arrays | Access and process array elements |
| Functions | Pass addresses and modify original objects |
| Linked lists | Connect nodes in a data structure |
| Trees | Link parent and child nodes |
| Polymorphism | Use base-class pointers to access derived objects |
| Function callbacks | Call functions indirectly |
| System programming | Work with memory and low-level interfaces |
Example: Using pointers in a linked-list node
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
int main() {
Node first{10, nullptr};
Node second{20, nullptr};
first.next = &second;
cout << first.data << endl;
cout << first.next->data << endl;
return 0;
}Output:
10
20The next pointer connects the first node to the second node. This is a basic example of how pointers are used to build linked lists.
16. Common Pointer Errors in C++
Pointers are powerful, but incorrect pointer usage can cause serious programming errors.
1. Uninitialized pointer
int* ptr;
// Dangerous: ptr does not point to a known object.Solution:
int* ptr = nullptr;2. Dereferencing a null pointer
int* ptr = nullptr;
// Dangerous: *ptr = 10;Solution: Check whether a pointer is non-null before dereferencing it.
3. Dangling pointer
A dangling pointer refers to an object whose lifetime has ended.
For example, returning the address of a local variable from a function creates a dangling pointer.
Solution: Do not use pointers after the pointed-to object's lifetime ends. Use appropriate ownership tools.
4. Memory leak
A memory leak occurs when dynamically allocated memory is not released and no longer has a usable owner.
Solution: Prefer RAII and smart pointers, or ensure every allocation is correctly released.
5. Double deletion
Deleting the same dynamically allocated object more than once causes undefined behavior.
Solution: Use clear ownership rules and prefer smart pointers.
6. Accessing memory outside an array
Pointer arithmetic beyond an array's valid range can cause undefined behavior.
Solution: Keep pointer operations within the array or its one-past position, and never dereference the one-past pointer.
17. Pointers vs References in C++
Pointers and references both allow indirect access to objects, but they have different properties.
| Feature | Pointer | Reference |
|---|---|---|
| Declaration | Uses * | Uses & |
| Initialization | Can be initialized later | Must be initialized when declared |
| Null state | Can be nullptr | Cannot be a null reference in normal valid use |
| Reassignment | Can point to another object | Cannot be reseated to another object |
| Access | Uses * to dereference | Used like the original variable |
| Arithmetic | Supported for suitable pointers | Not supported |
| Typical use | Optional objects and address-based operations | Required object parameters and aliases |
Example using a reference
#include <iostream>
using namespace std;
void update(int& value) {
value = 500;
}
int main() {
int number = 100;
update(number);
cout << number << endl;
return 0;
}Output:
500References are often a simpler choice when a function requires an existing object. Pointers are appropriate when the address itself or an optional object matters.
18. Best Practices for Using Pointers
Follow these practices when writing pointer-based C++ programs:
Initialize pointers before using them.
Use
nullptrto represent an empty pointer.Never dereference a null, dangling, or otherwise invalid pointer.
Avoid unnecessary manual memory allocation.
Prefer
std::vectorfor dynamic arrays.Prefer
std::unique_ptrfor exclusive dynamic ownership.Use
std::shared_ptronly when shared ownership is genuinely required.Match
newwithdeleteandnew[]withdelete[].Avoid returning pointers to local variables.
Keep pointer ownership and object lifetimes clear.
19. Frequently Asked Questions (FAQs)
Q1. What is a pointer in C++?
A pointer is a variable that stores the memory address of another object or function.
Q2. What is the use of a pointer?
Pointers are used for dynamic memory management, arrays, functions, linked lists, trees, polymorphism, and low-level programming.
Q3. What does the * operator mean in C++?
The * operator is used to declare a pointer and to dereference a pointer to access the object it points to.
Q4. What does the & operator mean in C++?
The & operator obtains the address of an object. It is also used in reference declarations, depending on its context.
Q5. What is a null pointer?
A null pointer does not point to a valid object or function. In modern C++, use nullptr to represent one.
Q6. What is pointer arithmetic?
Pointer arithmetic is the process of moving a pointer between elements of the same array, using operations such as ptr++ and ptr + n.
Q7. What is a double pointer?
A double pointer is a pointer that stores the address of another pointer. It is declared using two asterisks, such as int** ptr.
Q8. What is dynamic memory allocation?
Dynamic memory allocation allows a program to request memory during execution. C++ provides new and delete, while modern C++ also offers containers and smart pointers.
Q9. What is a dangling pointer?
A dangling pointer refers to an object whose lifetime has ended or whose storage is no longer valid for access.
Q10. Are pointers and arrays the same in C++?
No. Array names convert to pointers in many expressions, but arrays and pointers are different types with different properties.
Runnable Code Example: Pointers in C++
C++20 / C++23#include <iostream>
void modifyViaPointer(int* ptr) {
if (ptr != nullptr) {
*ptr = 999; // Dereference and write
}
}
int main() {
int sensorData = 100;
int* ptr = &sensorData; // Store address
std::cout << "Original Value: " << sensorData << "
";
std::cout << "Memory Address: " << ptr << "
";
std::cout << "Dereferenced: " << *ptr << "
";
modifyViaPointer(ptr);
std::cout << "After modification: " << sensorData << "
";
return 0;
}Common C++ Technical Interview Questions & Answers
Interview PrepQ: Why is nullptr superior to NULL in C++?
Q: What is a dangling pointer?
Key Takeaways, Modern Best Practices & Idioms
C++ Best Practices & Production Rules
nullptr or a valid memory address immediately.2. Check pointers for
nullptr before dereferencing.3. Use smart pointers (
std::unique_ptr) to eliminate raw ownership pointers.