An array of pointers is essentially an array where each element is a pointer. This is particularly useful when you need to manage a collection of dynamically allocated memory blocks, strings, or when dealing with arrays of arrays (e.g., for implementing 2D arrays).
This program will cover the following:
- Declaration of an array of pointers
- Dynamic memory allocation for each pointer
- Assignment of values to each dynamically allocated memory
- Accessing and printing the values
- Deallocating the memory
Here’s the complete program with explanations:
Example Program: Array of Pointers
#include <iostream>
using namespace std;
int main() {
const int size = 5; // Size of the array
int* arr[size]; // Declaration of an array of pointers
// Dynamic memory allocation and initialization
for (int i = 0; i < size; ++i) {
arr[i] = new int; // Allocate memory for each pointer
*arr[i] = (i + 1) * 10; // Assign values to allocated memory
}
// Print the values stored in the dynamically allocated memory
cout << “Values in the array of pointers:” << endl;
for (int i = 0; i < size; ++i) {
cout << *arr[i] << ” “; // Dereference pointer to get the value
}
cout << endl;
// Deallocate memory
for (int i = 0; i < size; ++i) {
delete arr[i]; // Free the allocated memory
}
return 0;
}
Explanation of the Program
-
Declaration of an Array of Pointers
Here, ‘arr’ is declared as an array of size (5) pointers to integers.
-
Dynamic Memory Allocation and Initialization
We loop through the array and allocate memory for each element using the ‘new’ operator. Then, we assign a value to each allocated memory location. In this example, the values assigned are 10, 20, 30, 40, and 50.
-
Accessing and Printing the Values
We loop through the array again and print the values stored at each pointer. Dereferencing ‘(*arr[i])’ is used to access the value at the memory address pointed to by ‘arr[i]’.
-
Deallocating Memory
Finally, we loop through the array and deallocate the memory for each pointer using the ‘delete’ operator to avoid memory leaks.
Advanced Example: Array of Pointers to Strings
Here’s an example that demonstrates an array of pointers to strings:
#include <iostream>
using namespace std;
int main() {
const int size = 3; // Size of the array
const char* arr[size] = {“Hello”, “World”, “Pointers”}; // Array of pointers to strings
// Print the strings stored in the array of pointers
cout << “Strings in the array of pointers:” << endl;
for (int i = 0; i < size; ++i) {
cout << arr[i] << endl; // Accessing the string literal
}
return 0;
}