In more advanced C++ applications, the dereference operator (*
) is frequently used in dynamic memory allocation, function arguments (pass-by-pointer), and handling complex data structures like arrays and linked lists. This example demonstrates the use of the dereference operator in dynamic memory allocation and pointer arithmetic to manipulate an array stored in the heap.
#include <iostream>
int main() {
// Dynamically allocate an array of 5 integers
int* arr = new int[5];
// Initialize values using pointer arithmetic
for (int i = 0; i < 5; i++) {
*(arr + i) = (i + 1) * 10; // Assign values: 10, 20, 30, 40, 50
}
// Display values using pointer dereferencing
std::cout << "Array values using pointer dereferencing: ";
for (int i = 0; i < 5; i++) {
std::cout << *(arr + i) << " "; // Dereference to access values
}
std::cout << std::endl;
// Modify values using pointer arithmetic
for (int i = 0; i < 5; i++) {
*(arr + i) += 5; // Increment each value by 5
}
// Display modified values
std::cout << "Modified array values: ";
for (int i = 0; i < 5; i++) {
std::cout << *(arr + i) << " ";
}
std::cout << std::endl;
// Free allocated memory
delete[] arr;
return 0;
}
int* arr = new int[5];
→ Allocates an integer array of size 5 in the heap.arr
stores the base address of this allocated memory.*(arr + i) = (i + 1) * 10;
assigns values 10, 20, 30, 40, 50
to the array.arr + i
moves the pointer to the i-th
index, and *
accesses/modifies the value.std::cout << *(arr + i);
retrieves values from the dynamically allocated array.*(arr + i) += 5;
increases each element by 5
.delete[] arr;
ensures proper memory management by deallocating the allocated memory.Array values using pointer dereferencing: 10 20 30 40 50
Modified array values: 15 25 35 45 55
This example highlights dynamic memory allocation, pointer arithmetic, and memory management, showing how the dereference operator (*
) is crucial in managing and manipulating dynamically allocated data in C++.