Arrays and Contiguous Data
Explore how arrays are used to store collections of data sequentially in memory, their declaration syntax, initialization methods, and how to safely access and iterate over elements. Understand the limitations of arrays and common pitfalls such as fixed size and lack of bounds checking, setting a foundation for safer C++ data management.
We'll cover the following...
In previous chapters, we covered the basic building blocks of program logic. We learned how to:
Store data in memory using variables.
Use
if/elseandswitchconstructs to control execution flow.Write loops to repeat actions.
Package a set of instructions into reusable function(s).
However, we hit a bottleneck when handling large sets of related data. Suppose, if we were building a weather application, we might need to store the temperature recorded each day for a month. Using thirty variables (e.g., temp1, temp2, temp3, and so on) to store this information is not a scalable approach. We need a way to store a collection of values under a single name. This brings us to the “arrays”.
How to define arrays
An array is a collection of elements of the same type, stored sequentially in memory. When we declare an array, we must tell the compiler two things: the type and the number of elements.
Syntax and constraints
The syntax for declaring an array is straightforward:
type name[size];
The type can be any fundamental type (like int, double, bool) or a user-defined types (which we will cover later). The size represents the capacity of the array.
There is a critical constraint here: the size of an array must be known at compile time. The compiler needs to know exactly how much memory to set aside for this variable before the program ever runs.
We cannot use a runtime variable (like a user input) to set the size of an empty array. We typically use an integer literal or a const variable for the size.
Visualizing array memory
When we write int scores[5];, the compiler allocates one continuous block of memory. If a single int occupies 4 bytes, the array uses exactly 20 bytes in total (5 elements × 4 bytes). This memory block contains only the integer values themselves. There is no stored size information, no header, no ...