Tie koodariksi

C++ Programming

Chapter 7: Arrays

Defining an array

An array is made up of consecutive items of the same type. For example, the following code creates an int array t with 5 elements:
int t[5];
If the array is defined within a function, its content is unformatted. If, on the other hand, the table is defined at the global level, each element of it is initially 0.

int a[5] = {3,2,4,8,2};
int b[5] = {0}; // {0,0,0,0,0}
int c[5] = {1}; // {1,0,0,0,0}

Array indexing

Items in an array are indexed with integers starting with 0. When an array contains n items, the first index is 0 and the last index is n-1. Here's how to work with an array:
t[0] = 5;
t[1] = 2;
t[2] = t[0]+t[1];
The following code prints the array contents with a for loop:
for (int i = 0; i < n; i++) {
    cout << t[i] << " ";
}

Multi-dimensional arrays

In a multi-dimensional array, each dimension corresponds a pair of square brackets. For example, the following code creates a two-dimensional table, which corresponds to a 4x7 grid.
int t[4][7];
To work with such a table:
t[0][0] = 2;
t[2][1] = 5;

Array restrictions

The arrays we have seen so far are static data structures, that is, they cannot be resized after definition.

There are no pre-defined functions in the array, where its content could be treated as a whole. Thus, the contents of an array cannot be directly copied, compared, or printed, and none of the following codes work for arrays:

a = b;
if (a == b)
cout << t << "\n";
If you need these features, they must be implemented by themselves, for example with a for loop.

In Chapter 14 we get to know the vector, which is a data structure like an array, but removes many of its limitations.

Arrays as parameters

Arrays behave differently as function parameters than do ordinary variables. An array is passed to a fuction as a pointer, means changes affect the caller.
void test(int t[]) {
    t[2] = 3;
}

int main() {
    int t[5] = {0};
    test(t);
    cout << t[2] << "\n"; // 3
}
A function does not know how many items are in an array. If this information is needed, it must be passed separately as another parameter, for example:
void test(int t[], int n) {
    for (int i = 0; i < n; i++) {
        cout << t[i] << "\n";
    }
}

Array overruns

C++ does not ensure that an array is used correctly. For example, the following code can be compiled and executed:
int t[5];
t[100] = 2;
This code creates an array with 5 elements, but then refers to the element at 100, which is outside the array. As a result, the program changes something in memory past the end of the array, which can lead to the program behaving strangely or crashing with an error.

Why doesn't C++ make sure the array is used correctly? The reason is performance: it would take time to check that the index is inside the array. C++ trusts that the programmer knows what they are doing.

Datatähti 2027 – peruskoulun ja lukion ohjelmointikilpailu käynnissä 26.10.–8.11.2026