How to Dynamically Allocate Memory for an Array of Strings?
Last Updated :
07 Feb, 2024
Dynamic memory and static memory are two types of memory allocation methods in C++ programming. Dynamic memory allows programmers to allocate memory to data structures at runtime. Dynamic memory can also be freed after work is done which also makes it more efficient.
In this article, we will learn how to allocate an array of strings in dynamic memory using pointers.
Allocate Memory to an Array of Strings Dynamically in C++
In C++, we can allocate and deallocate memory in the heap (dynamically) using new and delete keywords respectively. For an array of strings, we first need to allocate the memory for the array itself for the number of strings it’s going to store. Now, for each string, we will have to allocate memory according to the length of the string.
After usage, we will delete the allocated memory first string by string and then at last the main array.
C++ Program to Dynamically Allocate Memory for an Array of Strings using Pointers.
C++
#include <iostream>
using namespace std;
int main()
{
int n;
cout << "Enter the number of strings: " ;
cin >> n;
char ** strArray = new char *[n];
for ( int i = 0; i < n; i++) {
strArray[i] = new char [100];
cout << "Enter string " << i + 1 << ": " ;
cin >> strArray[i];
}
cout << "\nYou entered:\n" ;
for ( int i = 0; i < n; i++) {
cout << "String " << i + 1 << ": " << strArray[i]
<< endl;
}
for ( int i = 0; i < n; i++) {
delete [] strArray[i];
}
delete [] strArray;
return 0;
}
|
Output
Enter the number of strings: 3
Enter string 1: geeks
Enter string 2: for
Enter string 3: geeks
You entered:
String 1: geeks
String 2: for
String 3: geeks
Share your thoughts in the comments
Please Login to comment...