An array of pointers in is a collection where each element is a pointer, rather than a direct data value. This approach allows you to dynamically allocate memory, reference complex data structures, and achieve more flexibility with memory management. Let’s explore this concept in more detail:
An array of pointers is a standard C++ array where each element is a pointer that stores the address of a data element (like an integer, string, or object). This technique is especially useful when dealing with variable-sized data or when you want to manage memory dynamically.
The declaration of an array of pointers looks like this:
int* arr[5]; // Array of 5 integer pointers
Here, arr
is an array that can store 5 pointers to integers. Each element of arr
holds a pointer that can point to an integer.
#include <iostream>
int main() {
int a = 10, b = 20, c = 30;
int* arr[3]; // Array of pointers to integers
// Assigning addresses to the pointer array elements
arr[0] = &a;
arr[1] = &b;
arr[2] = &c;
// Accessing values using the array of pointers
for (int i = 0; i < 3; ++i) {
std::cout << "Value at arr[" << i << "] = " << *arr[i] << std::endl;
}
return 0;
}
Output:
Value at arr[0] = 10
Value at arr[1] = 20
Value at arr[2] = 30
You can also create an array of pointers to strings (character arrays). This allows you to manage and reference multiple strings efficiently.
#include <iostream>
int main() {
const char* arr[] = {"Hello", "World", "Array of Pointers"};
// Accessing strings using the array of pointers
for (int i = 0; i < 3; ++i) {
std::cout << "String " << i << ": " << arr[i] << std::endl;
}
return 0;
}
Output:
String 0: Hello
String 1: World
String 2: Array of Pointers
Arrays of pointers are also commonly used to create and manage collections of objects dynamically. For instance, you can create an array of pointers to objects of a class.
#include <iostream>
class Box {
public:
Box(int w, int h) : width(w), height(h) {}
void display() const {
std::cout << "Box with Width: " << width << " and Height: " << height << std::endl;
}
private:
int width;
int height;
};
int main() {
Box* boxes[3]; // Array of pointers to Box objects
// Creating objects and assigning them to the array of pointers
boxes[0] = new Box(3, 5);
boxes[1] = new Box(7, 10);
boxes[2] = new Box(4, 8);
// Accessing and displaying Box objects using the pointer array
for (int i = 0; i < 3; ++i) {
boxes[i]->display();
}
// Cleaning up dynamically allocated memory
for (int i = 0; i < 3; ++i) {
delete boxes[i];
}
return 0;
}
Output:
Box with Width: 3 and Height: 5
Box with Width: 7 and Height: 10
Box with Width: 4 and Height: 8