Dynamic Array Allocation in C++
Create an array sized at run time with new int[size] in C++, then find its sum, average, max, and min. Covers delete[], size 0, and why vector is safer.
1#include <iostream>2using namespace std;34int main() {5 int size;67 cout << "Enter array size: ";8 cin >> size;910 // Dynamically allocate array11 int* arr = new int[size];1213 cout << "Enter " << size << " elements: ";14 for (int i = 0; i < size; i++) {15 cin >> arr[i];16 }1718 cout << "\nArray elements: ";19 for (int i = 0; i < size; i++) {20 cout << arr[i] << " ";21 }22 cout << endl;2324 // Calculate sum25 int sum = 0;26 for (int i = 0; i < size; i++) {27 sum += arr[i];28 }2930 cout << "Sum: " << sum << endl;31 cout << "Average: " << (double)sum / size << endl;3233 // Find max and min34 int max = arr[0], min = arr[0];35 for (int i = 1; i < size; i++) {36 if (arr[i] > max) max = arr[i];37 if (arr[i] < min) min = arr[i];38 }3940 cout << "Maximum: " << max << endl;41 cout << "Minimum: " << min << endl;4243 // Free memory44 delete[] arr;45 arr = nullptr;4647 return 0;48}
Sample Output
Sum: 150
Total of the five values.
Average: 30
(double)150 / 5.
In this one
- How new int[size] creates an array sized at run time
- Why the pointer does not remember the size
- How (double)sum / size gives a decimal average
- Why delete[] is required at the end
How it works
- 1
Read size (5).
- 2
arr = new int[size].
- 3
Read five values and print them.
- 4
Compute sum 150, average 30, max 50, min 10.
- 5
delete[] arr and reset it.
Edge cases
Size 0
Enter 0.
new int[0] is legal, but max = arr[0] reads an element that does not exist (undefined), and sum / size divides by zero, giving nan. Check size > 0.
Negative size
Enter -3.
The size converts to a huge unsigned value and new throws std::bad_array_new_length (a kind of bad_alloc).
What's going on
A dynamic array is an array whose size you choose at run time. You read size from the user, then new int[size] reserves exactly that many ints on the heap. This is the standard way to do what int arr[n] only does as a compiler extension.
cin >> size; reads 5 in the sample. int* arr = new int[size]; returns a pointer to the first of five ints. From here on you use arr[i] exactly like a normal array, because arr[i] means *(arr + i).
The program then does three classic jobs. A loop reads the elements. Another sums them: 150. The average uses (double)sum / size so the division keeps decimals; with ints, 151 / 5 would print 30 instead of 30.2. The sample prints 30 because 150 / 5 is a whole number.
Max and min start at arr[0] and the loop begins at index 1. That avoids needing INT_MIN and INT_MAX, but it assumes there is at least one element.
delete[] arr; frees the block, with brackets because it came from new[]. Then arr = nullptr;.
The pointer does not know the array's size. You must keep size yourself, and nothing stops you from reading arr[size], which is past the end and undefined. vector<int> arr(size); remembers its size, offers at() with bounds checking, and frees itself.
The only header is <iostream>. It gives you cout for displaying output and cin for taking input from the user.
Understanding Dynamic Arrays
Dynamic Array Concept:
Advantages:
Allocating Dynamic Array
Basic Allocation:
int size;
cin >> size;
int* arr = new int[size];
What happens here:
Reading Array Elements
Input Loop:
for (int i = 0; i < size; i++) {
cin >> arr[i];
}
What happens here:
Processing Dynamic Array
Operations:
Example:
int sum = 0;
for (int i = 0; i < size; i++) {
sum += arr[i];
}
double average = (double)sum / size;
What happens here:
Freeing Dynamic Array
Deallocation:
delete[] arr;
arr = nullptr;
What happens here:
Important:
When to Use Dynamic Arrays
Best For:
Example Scenarios:
Important Considerations
Memory Management:
Stack vs Heap:
Size Limitations:
return 0;
This ends the program successfully.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Which statement frees this array correctly?
Pick an answer to check it.
Question 2
Where is the size of arr stored?
Pick an answer to check it.
Questions people ask
How is this different from int arr[size]?
int arr[size] with a run-time size is not standard C++. new int[size] is standard.
Can I resize it?
Not in place. Allocate a bigger block, copy, and delete the old one, or use vector.
Why cast to double?
So the division is floating-point and keeps the fraction.