Dynamic Array of Pointers to Strings in C++
All the above declarations are static and will be allocated in the heap. We can also create a dynamic array of pointers to strings using the new keyword.
Syntax of Dynamic Array of Pointers to Strings
char** array_name = new char*[size] {initial values....}
In this way, we will create an array of pointer which is stored inside the heap memory. But the strings will still be stored in the read only memory. To store the strings in the dynamic memory, we will have to create a new memory block for each element of this array.
char** array_name = new char*[size];
array_name[i] = new char[strlen("value")];
strcpy(array_name[i], "value");
We can do this for dynamic array of pointer to strings OR…… we can directly use the inbuit containers for dynamic array and strings namely std::vector and std::string where we dont have to worry about size every time we do something.
Example of Dynamic Array of Pointers to String
// C++ Program to illustrate how to create a dynamic array
// of pointers to strings
#include <cstring>
#include <iostream>
#include <string>
#include <vector>
#define SIZE 3
using namespace std;
// driver code
int main()
{
// first method to create a dynamic array of pointers to
// strings
char** names1
= new char* [SIZE] { "Geek", "Geeks", "Geeksfor" };
// second method
char** names2 = new char*[SIZE];
// adding elements
names2[0] = new char[strlen("Ram")];
strcpy(names2[0], "Ram");
names2[1] = new char[strlen("Arun")];
strcpy(names2[1], "Arun");
names2[2] = new char[strlen("Vivek")];
strcpy(names2[2], "Vivek");
// using vector and strings
vector<string*> names3;
names3.push_back(new string("Geek"));
names3.push_back(new string("Geeks"));
names3.push_back(new string("Geeksfor"));
// printing all
cout << "First Array: ";
for (int i = 0; i < SIZE; i++) {
cout << names1[i] << " ";
}
cout << endl;
cout << "Second Array: ";
for (int i = 0; i < SIZE; i++) {
cout << names2[i] << " ";
}
cout << endl;
cout << "Last Array: ";
for (int i = 0; i < SIZE; i++) {
cout << *names3[i] << " ";
}
// freeing all memory
delete[] names1;
for (int i = 0; i < SIZE; i++)
delete[] names2[i];
delete[] names2;
// vector of string pointer will be deleted
// automatically
return 0;
}
Output
First Array: Geek Geeks Geeksfor Second Array: Ram Arun Vivek Last Array: Geek Geeks Geeksfor
Array of Pointers to Strings in C++
In C++, an array is a homogeneous collection of data that is stored in a contiguous memory location. We can store almost all types of data as array elements. In this article, we will learn how to store the array of pointers to strings in C++.