Core C++

Lesson 10 : One-Dimensional Arrays


Reference page for this video tutorial: Arrays.

An array is a collection of data elements of the same type. Since it holds multiple data elements, we call the array an aggregate type. As an example, we can create an array of 10 doubles:

This line is called a declaration and it introduces the array's name and specifies the type in the program. The size of the array is 10. For arrays, sizes must be compile-time constants. That is, we cannot declare an array like this:

This code causes a compilation error since the compiler does not know the size of the array; it is determined at run-time.


Array indices begin at 0 in C++. So, an array with ten elements is indexed by the integer 0-9. Using the bracket operator, we can access individual elements of the array:

There are several different ways to initialize an array. After declaration, we can fill the array with one value at a time using the bracket operator:

We can also declare and initialize the array at the same time with a size parameter:

Otherwise, we can declare and initialize the array with no size parameter:

In the last case, the compiler figures out the size of the array for us.


Arrays cannot be copied via the assignment operator as we do with other variable types. This, for example, will generate a compilation error:

Instead, we must copy each entry of the array, one at a time like this:

Similarly, we cannot output an entire array to the console all at once in this manner.

Instead, we have to output each element individually. Trying to output an array will not generate an error, but it will output the address of the array in memory—not really a useful thing to do.


Due to legacy usage char arrays have some unique characteristics. Prior to C++, char arrays were the way to represent strings of text, such as names, inside of a program. Currently, this is done with the more functional string type, which will cover later. However, to accommodate older code usage, char arrays have some non-standard usage. For example, we can initialize a char array with a string in quotation marks:

We can also input or output an entire char array, unlike other arrays.

Note that when we use char arrays like this, we must be sure to have a zero at the end of the array. For the initializations above, the zero is added at the end of the array automatically.

 

© 2007–2024 XoaX.net LLC. All rights reserved.