C++ Dynamic Memory Allocation: Array of integers and strings initialization
2. Dynamically Allocate an Array of Integers and Strings
Write a C++ program to dynamically allocate an array of integers and strings and initialize its elements.
Sample Solution:
C Code:
Sample Output:
Dynamically allocated integer array: 1 2 3 4 5 6 7 Dynamically allocated string array: Element-1 Element-2 Element-3 Element-4 Element-5 Element-6 Element-7
Explanation:
In the above exercise -
- Use the new operator to dynamically allocate memory for an array of integers and strings. The array size is determined by the variable size.
- Initialize the integer array with values from 1 to size using a for loop. Similarly, initialize the string array elements with strings like "Element 1", "Element 2", etc.
- Next display the elements of both arrays using std::cout. The integer array elements are displayed on a single line separated by spaces, while the string array elements are displayed one per line.
- Finally, deallocate dynamically allocated memory using the delete[] operator for both arrays.
Flowchart:

For more Practice: Solve these Related Problems:
- Write a C++ program to dynamically allocate an array of 10 integers and initialize each element with its index value multiplied by 2, then print the array.
- Write a C++ program to dynamically allocate an array of strings of size n (input by the user) and populate each element with a default message, then display the array.
- Write a C++ program to create two dynamic arrays—one for integers and one for strings—and initialize them with random numbers and sample text respectively, then print both arrays side by side.
- Write a C++ program to dynamically allocate an array of integers and another array of strings, then allow the user to input values for both and display them in a formatted table.
CPP Code Editor:
Contribute your code and comments through Disqus.
Previous C++ Exercise: Integer, character, string assignment.
Next C++ Exercise: Initializing 2D arrays of floats and strings.
What is the difficulty level of this exercise?