C++ Programming
Pointers and References
Master C++ programming from basics to advanced. Learn object-oriented programming, STL, memory management, and build high-performance applications.
On this page
Pointers and References
Pointers and references are powerful features in C++ that allow you to work directly with memory addresses. They're essential for efficient memory management and advanced programming.
What are Pointers?
A pointer is a variable that stores the memory address of another variable. Instead of storing a value, it stores where the value is located in memory.
Key Concepts:
- Address: Location in memory where data is stored
- Pointer: Variable that holds an address
- Dereference: Accessing the value at an address
Pointer Declaration
Syntax:
1type* pointerName;
Example:
1int* ptr; // Pointer to int
2double* dptr; // Pointer to double
3char* cptr; // Pointer to char
Address-of Operator (&)
Gets the memory address of a variable:
1int num = 10;
2int* ptr = # // ptr now holds address of num
Dereference Operator (*)
Accesses the value at the address stored in a pointer:
1int num = 10;
2int* ptr = #
3cout << *ptr << endl; // Prints 10 (value at address)
Basic Pointer Operations
Example:
1int num = 10;
2int* ptr = #
3
4cout << "Value of num: " << num << endl; // 10
5cout << "Address of num: " << &num << endl; // Memory address
6cout << "Value of ptr: " << ptr << endl; // Same address
7cout << "Value at ptr: " << *ptr << endl; // 10
Sample Output
Value of num: Address of num: Value of ptr: Value at ptr:
Modifying Values Through Pointers
Example:
1int num = 10;
2int* ptr = #
3
4*ptr = 20; // Changes num to 20
5cout << num << endl; // 20
Null Pointers
Pointers that don't point to anything:
1int* ptr = nullptr; // C++11 (preferred)
2int* ptr2 = NULL; // C-style
3int* ptr3 = 0; // Also valid
Always initialize pointers! Uninitialized pointers contain garbage addresses.
Pointer Arithmetic
Pointers can be incremented/decremented to move to adjacent memory locations:
1int arr[5] = {10, 20, 30, 40, 50};
2int* ptr = arr; // Points to first element
3
4cout << *ptr << endl; // 10
5ptr++; // Move to next element
6cout << *ptr << endl; // 20
7ptr += 2; // Move 2 elements forward
8cout << *ptr << endl; // 40
Important: Pointer arithmetic depends on the size of the data type.
Pointers and Arrays
Arrays and pointers are closely related:
1int arr[5] = {10, 20, 30, 40, 50};
2int* ptr = arr; // Array name is pointer to first element
3
4// These are equivalent:
5cout << arr[0] << endl; // 10
6cout << *arr << endl; // 10
7cout << ptr[0] << endl; // 10
8cout << *ptr << endl; // 10
Pointers as Function Parameters
Passing pointers allows functions to modify original values:
1void swap(int* a, int* b) {
2 int temp = *a;
3 *a = *b;
4 *b = temp;
5}
6
7int main() {
8 int x = 10, y = 20;
9 swap(&x, &y); // Pass addresses
10 cout << x << " " << y << endl; // 20 10
11 return 0;
12}
Dynamic Memory Allocation
new Operator
Allocates memory at runtime:
1int* ptr = new int; // Allocate single integer
2*ptr = 10;
3
4int* arr = new int[5]; // Allocate array of 5 integers
5arr[0] = 10;
6arr[1] = 20;
delete Operator
Frees allocated memory:
1int* ptr = new int;
2*ptr = 10;
3delete ptr; // Free single variable
4ptr = nullptr; // Good practice
5
6int* arr = new int[5];
7delete[] arr; // Free array (use delete[])
8arr = nullptr;
Important Rules:
- Every
newmust have a correspondingdelete - Use
deletefor single variables,delete[]for arrays - Set pointer to
nullptrafter deletion - Never delete the same pointer twice
Memory Leaks
Memory leaks occur when allocated memory is not freed:
1void leak() {
2 int* ptr = new int[1000];
3 // Forgot to delete - memory leak!
4}
Prevention:
- Always match
newwithdelete - Use smart pointers (we'll cover later)
- Use RAII (Resource Acquisition Is Initialization)
What are References?
A reference is an alias (another name) for an existing variable. Unlike pointers, references must be initialized and cannot be reassigned.
Key Differences from Pointers:
- Must be initialized when declared
- Cannot be reassigned to point to another variable
- No need for dereference operator
- Cannot be null
Reference Declaration
Syntax:
1type& refName = variable;
Example:
1int num = 10;
2int& ref = num; // ref is alias for num
3
4ref = 20; // Changes num to 20
5cout << num << endl; // 20
References as Function Parameters
References allow functions to modify original values without pointers:
1void swap(int& a, int& b) {
2 int temp = a;
3 a = b;
4 b = temp;
5}
6
7int main() {
8 int x = 10, y = 20;
9 swap(x, y); // Pass variables directly
10 cout << x << " " << y << endl; // 20 10
11 return 0;
12}
Benefits:
- Cleaner syntax (no
&when calling) - No need to check for null
- Cannot be reassigned accidentally
Const References
Prevent modification while avoiding copying:
1void print(const int& value) {
2 cout << value << endl;
3 // value = 10; // Error: cannot modify const reference
4}
Use const references for:
- Large objects (avoid copying)
- Parameters that shouldn't be modified
- Read-only access
Pointers vs References
| Feature | Pointer | Reference |
|---|---|---|
| Declaration | int* ptr; | int& ref = var; |
| Initialization | Can be null | Must initialize |
| Reassignment | Can change | Cannot change |
| Null value | Can be null | Cannot be null |
| Dereference | Need * | Automatic |
| Address | Has own address | Same as variable |
When to use:
- Pointers: Dynamic memory, optional parameters, arrays, C compatibility
- References: Function parameters, return values, aliases
Pointer to Pointer
Pointers can point to other pointers:
1int num = 10;
2int* ptr = #
3int** pptr = &ptr; // Pointer to pointer
4
5cout << num << endl; // 10
6cout << *ptr << endl; // 10
7cout << **pptr << endl; // 10
Function Pointers
Pointers that point to functions:
1int add(int a, int b) {
2 return a + b;
3}
4
5int main() {
6 int (*funcPtr)(int, int) = add;
7 int result = funcPtr(5, 3); // Calls add(5, 3)
8 return 0;
9}
Common Patterns
Pattern 1: Swap Function
1void swap(int& a, int& b) {
2 int temp = a;
3 a = b;
4 b = temp;
5}
Pattern 2: Array Parameter
1void printArray(int* arr, int size) {
2 for (int i = 0; i < size; i++) {
3 cout << arr[i] << " ";
4 }
5}
Pattern 3: Return by Reference
1int& getElement(int* arr, int index) {
2 return arr[index];
3}
4
5// Usage
6int arr[5] = {1, 2, 3, 4, 5};
7getElement(arr, 2) = 99; // Modifies arr[2]
Best Practices
- ✅ Always initialize pointers (use
nullptr) - ✅ Check for null before dereferencing pointers
- ✅ Match new with delete (and new[] with delete[])
- ✅ Set pointers to nullptr after deletion
- ✅ Use references for function parameters when possible
- ✅ Use const references for read-only parameters
- ✅ Avoid raw pointers when smart pointers are available
- ✅ Prefer references over pointers when null isn't needed
Common Mistakes
- ❌ Dereferencing null or uninitialized pointers
- ❌ Memory leaks (forgetting to delete)
- ❌ Double deletion (deleting same pointer twice)
- ❌ Using deleted memory
- ❌ Array bounds violations with pointers
- ❌ Mixing up
*(dereference) and&(address-of) - ❌ Trying to reassign references
Next Module
In Module 8, we'll learn about Object-Oriented Programming - how to create classes and objects to model real-world entities!
Hands-on Examples
Basic Pointer Operations
#include <iostream>
using namespace std;
int main() {
int num = 10;
int* ptr = # // ptr stores address of num
cout << "Value of num: " << num << endl;
cout << "Address of num: " << &num << endl;
cout << "Value of ptr (address): " << ptr << endl;
cout << "Value at ptr: " << *ptr << endl;
// Modifying through pointer
*ptr = 20;
cout << "After *ptr = 20, num = " << num << endl;
// Pointer arithmetic
int arr[5] = {10, 20, 30, 40, 50};
int* arrPtr = arr;
cout << "\nArray via pointer:" << endl;
for (int i = 0; i < 5; i++) {
cout << "arr[" << i << "] = " << *(arrPtr + i) << endl;
}
return 0;
}Pointers store memory addresses. Use & to get address, * to dereference. Pointers can be used to access and modify values indirectly. Pointer arithmetic allows moving through arrays.
Sample Output
Value of num: 10 Address of num: 0x7fff5fbff6ac Value of ptr (address): 0x7fff5fbff6ac Value at ptr: 10 After *ptr = 20, num = 20 Array via pointer: arr[0] = 10 arr[1] = 20 arr[2] = 30 arr[3] = 40 arr[4] = 50
Practice with Programs
Reinforce your learning with hands-on practice programs
Related Program Topics
Recommended Programs
Array Max & Min
BeginnerFind the largest and smallest values in a C++ array in one pass, starting from INT_MIN and INT_MAX. Traces 10 5 20 15 8 and shows why starting at 0 fails.
Array Average
BeginnerCompute the average of n numbers stored in a C++ array, adding them up as they are read. Covers double for the sum, setprecision(2), and the n = 0 trap.
Merge Arrays
BeginnerMerge two integer arrays into one in C++ by copying the first array, then the second after it. Learn the n1 + i offset and how to size the merged array.