dynamic memory allocation for string in c++

Dynamic Memory Allocation for String in C++

#include <iostream>
#include <string>

int main() {
    std::string *ptrToString = new std::string; // Step 1: Declare a pointer for the string and allocate memory using new keyword
    *ptrToString = "Dynamic allocation for string"; // Step 2: Assign a value to the dynamically allocated string using the pointer
    std::cout << *ptrToString << std::endl; // Step 3: Make use of the dynamically allocated string
    delete ptrToString; // Step 4: Deallocate the memory using delete keyword
    return 0;
}
  1. Declare a pointer and allocate memory: Declare a pointer for the string and allocate memory using the new keyword.
  2. Assign a value: Assign a value to the dynamically allocated string using the pointer.
  3. Make use of the allocated string: Make use of the dynamically allocated string, for example, by printing it.
  4. Deallocate the memory: Deallocate the memory using the delete keyword to prevent memory leaks.