Back to: C
definition
An array is a data structure that can store multiple values in a variable, in sequential order. The values that are stored in an array must be of the same data type (all ints, floats etc)!
declaration
This is how you declare an array:
type name[size];
An example:
int the_num[8];
First, you declare the data type. Then a name, along with square brackets. In the square brackets you place the number of values the array can store. The statement is then ended with a semi-colon.
Once the type of data that can be stored and the size has been set, you cannot change the type of data that can be stored and/or the number of values that it can store!
update
I stated that “Once the type of data that can be stored and the size has been set, you cannot change the type of data that can be stored and/or the number of values that it can store!“
This statement was true, up until the release of C99. With C99 the concept of variable length arrays was introduced. This allowed for arrays whose length is determined at runtime, rather than compile time!
This concept in C has caused much debate. There’s nothing inherently wrong with the idea but purists reject it and I think that there are some fair arguments to be made, that in certain situations (such as embedded systems, where memory is limited) that they could cause problems. However, you can also make the argument that if the correct precautions are taken, there shouldn’t be such problems! Many pages could (and have) been written on this!
initialisation
initialisation during declaration
We can initialise an array during declaration. We add the assignment operator and insert values into curly braces, separating each value with a comma:
type name[size] = {value1, value2, value3}
Using our example:
int the_num[8] = {22, 44, 22, 45, 45, 56, 34, 56};
An important point to note is that even though I stated that the integer would have a size of 8, it is valid to assign less than 8 values to it! If you do this, then the remainder of the positions are given a value of 0.
Also, you can initialise an array without specifying the size:
int the_num = {22, 44, 22, 45, 45, 56, 34, 56};
This is valid and works because the compiler knows the size by looking out the number of positions in the array.
accessing elements
To access an element in an array we need to specify the index of the element by using square brackets:
name[element_index]
In C an array index starts with 0. Therefore the first item has an index of 0, the second an index of 1 etc.