Open In App

How to Dynamically Allocate Memory for an Array of Strings?

Last Updated : 07 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// Program to dynamically allocate memory for an array of
// strings
  
#include <iostream>
  
using namespace std;
  
int main()
{
    int n;
    cout << "Enter the number of strings: ";
    cin >> n;
  
    // Dynamically allocate memory for an array of pointers
    // to char
    char** strArray = new char*[n];
  
    // Allocate memory for each string and get input from
    // the user
    for (int i = 0; i < n; i++) {
        // Assuming the string will be
        // less than 100 characters
        strArray[i] = new char[100];
        cout << "Enter string " << i + 1 << ": ";
        cin >> strArray[i];
    }
  
    // Display the strings
    cout << "\nYou entered:\n";
    for (int i = 0; i < n; i++) {
        cout << "String " << i + 1 << ": " << strArray[i]
             << endl;
    }
  
    // Deallocate the memory
    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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads