An array in C++ can be declared as follows:
#include <iostream> using namespace std; int main() { int array[ 5 ]; // declare an "array" of 5 integers // fill slots 0-4 with values array[ 0 ] = 1; array[ 1 ] = 2; array[ 2 ] = 3; array[ 3 ] = 4; array[ 4 ] = 5; // print out the contents for( int index = 0; index < 5; index++ ) cout << array[ index ] << endl; }
The way this looks in memory is something like this:
That is, inside the array
variable are five slots or elements. Inside each of the slots is a regular int
variable.
So, how do you access one of the int
values in the array? To access the individual elements of an array, we use square brackets, as shown in the following line of code:
array[ 0 ] = 10;
The preceding line of code would change the element at slot 0 of the array to a 10:
In general, to get to a particular slot of an array, you will write the following:
array[ slotNumber ] = value to put into array;
Keep in mind that array slots are always indexed starting from 0. To get into the first slot of the array, use array[0]
. The second slot of the array is array[1]
(not array[2]
). The final slot of the array above is array[4]
(not array[5]
). The array[5]
data type is out of bounds of the array! (There is no slot with index 5 in the preceding diagram. The highest index is 4.)
Don't go out of bounds of the array! It might work some times, but other times your program will crash with a memory access violation (accessing memory that doesn't belong to your program). In general, accessing memory that does not belong to your program is going to cause your app to crash, and if it doesn't do so immediately, there will be a hidden bug in your program that only causes problems once in a while. You must always be careful when indexing an array.
Arrays are built into C++, that is, you don't need to include anything special to have immediate use of arrays. You can have arrays of any type of data that you want, for example, arrays of int
, double
, string
, and even your own custom object types (Player
).
#include <iostream> #include <string> using namespace std; int main() { string array[ 5 ]; // declare an "array" of 5 strings // fill slots 0-4 with values array[ 0 ] = "Mariam McGonical"; array[ 1 ] = "Wesley Snice"; array[ 2 ] = "Kate Winslett"; array[ 3 ] = "Erika Badu"; array[ 4 ] = "Mohammad"; // print out the contents for( int index = 0; index < 5; index++ ) cout << array[ index ] << endl; }
double temps[ 3 ]; // fill slots 0-2 with values temps[ 0 ] = 0; temps[ 1 ] = 4.5; temps[ 2 ] = 11;
3.147.72.74