Creating and using arrays
In C, once you create an array, the type and size must be declared, and those values are immutable. In other words, the size cannot be made greater or smaller, and the data type stored inside cannot be changed (e.g. you can't change it so it stores floats if the type was declared as integer when the array was created).
To put it more succinctly: arrays in C are data structure with a fixed number of items that are all the same type.
Declaring an array
Declaring an array is similar to variable declaration, with the brackets at the end indicating size. Declare them using the following format:
dataType arrayName[numberOfElements];
int myArray[10];
Arrays act much like they do in other languages:
- Arrays are zero-indexed (start at 0). Access elements using the index number, e.g. myArray[4] will get the 5th element of the array. Expressions can also be placed inside the brackets, e.g. myArray[myArray.length -1]
- The compiler will not catch out of bounds errors. Using an expression or variable for an index value that is outside the bounds of the array will cause problems, known as an out of bounds error, which can cause the program to crash, or other errors in the program that will cause it to malfunction.
- One thing to bear in mind that can be a bit confusing for new programmers, is that even though arrays are zero-indexed, the numbers used when declaring them are not. So array[10] creates an array with ten elements, but their indexes run from 0 through 9.
Assignment
Elements values are assigned as in other languages:
myArray[4] = 123; // assigns the value 123 to the fifth element of the array
Initializing an array (assigning initial values)
To declare an array and initialize with values, provide the values inside a pair of curly brackets, separated by commas:
int myArray[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
If elements are not assigned, they will be set to 0.
In the C99 standard, the index can be specified in the curly brackets, in any order:
float myArray[4] = {[2] = 500.5, [1] = 300.0, [0] = 100.0};
// results in array [100.0, 300.0, 500.5, 0, 0]
Note that, if the index is specified, as in the above example, the following elements will count up from the last assigned element.
float myArray[10] = {[2] = 500.5, 300.0, [7] = 100.0};
//results in array [0, 0, 0, 500.5, 300.0, 0, 0, 0, 100.0, 0, 0]
There is no shortcut to assign all elements to the same value like some other languages provide.
If you want to assign many of the same or sequential values at the same time, your best bet is to use a for loop.
Variable length arrays
The name is a bit misleading -- what variable length in this case means in this case that you can specify the size of the array with a variable. The array itself will stay the same size after creation and cannot be altered. This feature was introduced in C99, mainly to make C work better with other libraries or languages such as Fortran, and may be referenced in documentation.
int n = 10;
int myArray[n]
Multi-Dimensional arrays
Multi-dimensional arrays, or nested arrays, are arrays that contain arrays as their elements. A good way to visualize a 2-dimensional array (2D array) is like a spreadsheet: each element of the main array is a row, and each element of the inner arrays (subarrays) are columns. Each element of the subarrays are one cell of a row, in that column. In other words, it would be:
array[rows][columns].
int mySpreadsheet[4][5];
// creates an empty array [[], [], [], []]
int mySpreadsheetFilled[4][5] = {
{1, 2, 3, 4, 5},
{6, 7, 8, 9, 10},
{11, 12, 13, 14, 15},
{16, 17, 18, 19, 20}
};
// creates an array that looks like the below
// [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]
An easy way to immediately know how many dimensions are in an array is how many pairs of brackets there are. The first array above is 2 dimensions: mySpreadsheet[4][5]. A third pair would mean it's a 3D array: mySpreadsheet[4][5][6].
I find it much easier to mentally visualize the 2D arrays as an actual spreadsheet. The one created in the code above would appear as the table below:
1 | 2 | 3 | 4 | 5 |
---|---|---|---|---|
6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 |
Or, another way to display it would be (top row is the Outer Array Indexes, the inner arrays are in the rows below):
0 | 1 | 2 | 3 | 4 |
---|---|---|---|---|
1 | 2 | 3 | 4 | 5 |
6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 |
All elements do not have to be assigned when the array is created. Any elements that are not initialized with values will be filled with zeroes.
As explained above, the C99 standard allows specific indices to be assigned in any order, using the square bracket notation:
int myNewArr[3][2] = {[0][0] = 1, [1][0] = 5}
// creates an array [[1, 0], [5, 0], [0, 0]]
A 3D array can be visualized as a stack of spreadsheets or data tables. In practice, 3D and larger arrays are not used that frequently because it can become confusing, and accessing elements can be a pain, but it is good to know that they exist. If a data structure larger than a 2D array is needed, most likely a database would be employed.
3D arrays are initialized the same way as a 2D array, just adding another level of brackets for the third level of the array.
Dealing with array data
Most commonly, arrays are accessed using loops (usually the good old 'for' loop), and so to access the data in each dimension will require one more level of nested loop to access. Easiest way to remember is that the number of loops is the same as the dimensions of the array:
1D array: single loop
2D array: 2 levels of loops (nested)
3D array: 3 levels of loops (nested)
...etc.
Top comments (2)
Very useful! Assigning by index was news to me.
I think both of those float array comments have too many elements, no?
and
I think this bit is a little misleading:
That is true, if some/any of the elements are assigned. But if the local array is only declared, like
the values are garbage. On the other hand, if the array is declared globally outside of all functions, the values actually are implicitly initialized to 0 even if no value is assigned.
I just learned that there is a very naughty non-standard way to do that like this:
where you give a range of indices and the value you want to set those to.
But not all compilers support it, and ISO C forbids it, so probably better not to get used to it and just use loops like you said.
Huh, TIL
float myArray[4] = {[2] = 500.5, [1] = 300.0, [0] = 100.0};
. Good to know, thanks for the write-up.