Course offer · HLD · LLD · System Design at ₹799 until 30 Nov (not interview packs)

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.

BeginnerMemory Management ProgramsExample 8 of 11
dynamic-array-allocation.cpp
1#include <iostream>
2using namespace std;
3
4int main() {
5 int size;
6
7 cout << "Enter array size: ";
8 cin >> size;
9
10 // Dynamically allocate array
11 int* arr = new int[size];
12
13 cout << "Enter " << size << " elements: ";
14 for (int i = 0; i < size; i++) {
15 cin >> arr[i];
16 }
17
18 cout << "\nArray elements: ";
19 for (int i = 0; i < size; i++) {
20 cout << arr[i] << " ";
21 }
22 cout << endl;
23
24 // Calculate sum
25 int sum = 0;
26 for (int i = 0; i < size; i++) {
27 sum += arr[i];
28 }
29
30 cout << "Sum: " << sum << endl;
31 cout << "Average: " << (double)sum / size << endl;
32
33 // Find max and min
34 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 }
39
40 cout << "Maximum: " << max << endl;
41 cout << "Minimum: " << min << endl;
42
43 // Free memory
44 delete[] arr;
45 arr = nullptr;
46
47 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. 1

    Read size (5).

  2. 2

    arr = new int[size].

  3. 3

    Read five values and print them.

  4. 4

    Compute sum 150, average 30, max 50, min 10.

  5. 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:

Size determined at runtime
Allocated on heap (not stack)
Can be much larger than stack arrays
Must be explicitly freed

Advantages:

Size not fixed at compile time
Can handle large arrays
Flexible memory usage
User-determined sizes

Allocating Dynamic Array

Basic Allocation:

int size;

cin >> size;

int* arr = new int[size];

What happens here:

Size obtained from user at runtime
new[] allocates memory for size elements
Returns pointer to first element
Can access like regular array: arr[0], arr[1]

Reading Array Elements

Input Loop:

for (int i = 0; i < size; i++) {

cin >> arr[i];

}

What happens here:

Reads elements one by one
Stores in dynamically allocated array
Same syntax as regular arrays
Size can be any value (within memory limits)

Processing Dynamic Array

Operations:

Sum: add all elements
Average: sum / size
Max/Min: find largest/smallest

Example:

int sum = 0;

for (int i = 0; i < size; i++) {

sum += arr[i];

}

double average = (double)sum / size;

What happens here:

Process elements like regular arrays
All standard array operations work
Size is known (stored in variable)

Freeing Dynamic Array

Deallocation:

delete[] arr;

arr = nullptr;

What happens here:

delete[] frees entire array
Returns memory to system
Prevents memory leak
Set to nullptr for safety

Important:

Always use delete[] (not delete)
Must match new[] with delete[]
Forgetting delete[] causes memory leak

When to Use Dynamic Arrays

Best For:

Size unknown at compile time
Large arrays (avoid stack overflow)
User-determined sizes
Variable-sized data structures
Runtime configuration

Example Scenarios:

Reading file data (unknown size)
User input arrays
Large matrices
Dynamic data processing

Important Considerations

Memory Management:

Always delete[] what you new[]
Memory leak if not freed
Can cause program to run out of memory
Set pointer to nullptr after deletion

Stack vs Heap:

Stack arrays: fixed size, limited size
Heap arrays: dynamic size, much larger
Stack overflow for large arrays
Heap allows larger allocations

Size Limitations:

Heap can handle much larger arrays
Limited by available memory
Stack typically limited to few MB
Heap can use GB (system dependent)

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.