Allocating 1-D Arrays on Heap

Discover the power of dynamic allocations and learn how to allocate one-dimensional arrays on the heap.

Introduction

Allocating variables dynamically on the heap is interesting, but that’s not where the heap shines. To show the true power of the heap, we’ll learn how to dynamically allocate arrays.

Consider the following motivating example. We want to read integer temperature samples from a file called temperature_samples.txt. The file can contain an arbitrary number of samples, depending on how many temperatures were registered.

On the first line, there will be a number n, the number of samples. On the next, n lines will be n samples, each on one line.

We may do this because we want to calculate the minimum, maximum, and average temperature (or for any other reason). We’ll design part of the code which reads and stores the temperatures inside an array.

Stack array solution

Imagine we don’t know about dynamic allocations. Then, the only solution we can think of is to use a stack array.

Note: Don’t stress too much about the file reading part. We’ll explain it briefly, but the file is there to show a concrete scenario where dynamic allocations are needed.

See a potential solution below:

Get hands-on with 1200+ tech skills courses.