# C++ Arrays¶

C++, like most other programming languages, supports the building of a data structure that can hold a number of identical objects. This objects can be standard data items, or objects you create with classes. When you set up an array, you must decide how big it will be when you compile your program. It cannot grow later. There are ways to solve this limitation, but we will explore them later!

Here is a simple array declaration:

int grades[5] = { 99, 87, 53, 75, 95 };


The square brackets after the name grades in this case, tell the system to set up exactly 5 containers. We will access those containers by using the array name, and providing a subscript which can be a literal number, or a variable whose value is in the limits of the array size.

Warning

It is a HUGE mistake to ask for grades[5], even though these are 5 items defined. The first subscript, or index is zero, so the last one is one less than the number used to set the array up!

Your code can access a container outside the defined range, but doing so is asking for trouble! Don’t do that, even by accident!

If you started working in Python, it will be annoying to find out that once you set up an array, you cannot decide to put another data type in the container, even though Python allows this. C++ is called strongly typed and enforces the type declarations you make in your code.

## Arrays of Objects¶

Now that we know about classes, we might find it handy to have an array of objects (like poolballs for example).

  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 #include using namespace std; #define MAX_SIZE 5 class SimpObj { public: int value; }; int main() { SimpObj objs[5]; int simple_ints[6] = { 5, 4, 3, 2, 1, 0 }; // initialize the array objects for( int i=0; i< MAX_SIZE; i++ ) objs[i].value = simple_ints[i]; for(int i=0; i<6;i++) { cout << simple_ints[i] << "="; cout << objs[i].value << " "; } cout << endl; for(int i=0; i< MAX_SIZE; i++) cout << objs[i].value - i << " "; cout << endl; } 

The output from this tes is a bit surprising:

\$ ./test
5=5 4=4 3=3 2=2 1=1 0=32767
5 3 1 -1 -3


Look closely at the code. I over-indexed the arrays on the output loop. Everything looked fine up until we went past the actual last point in the two arrays. Then we stepped on ourselves. The second line should have been identical to the first (minus the extra output from our objects), but the values got smashed.

Welcome to array indexing issues. You need to be careful when accessing arrays, or this kind of problem can lead to much lost time trying to figure out what happened!

This example should get you started with this.

Let’s look at examples of using arrays in the next lecture.