Arrays
Rather than go through all of the things involing arrays which would be rather tedious, some useful tricks and some infomation is presented about arrays.Arrays and Pointers
In C an array can 'decay' into a pointer when passed you set a pointer equal to an array, or pass it to a function, indeed functions do not take arrays but pointers instead. The pointer to an array will point to the address of the first element of an array.If you want the address of the first element in an array you do not need to use the
&operator on the array you can simply use its name, this can be seen in the example below.
Once an array has decayed it no longer has any size infomation assosiated with it. This means that you need to pass the size of an array in terms of the number of elements to a function since it cannot tell otherwise.
The array subscript operator []
The array operator acts on an array and is equivalent to addingito the address of the first element and derefering the resulting memory address where i is the ith element ie [2]. This can be seen in the example below:
int arr[] = {1,2,3}; int *ptr = array; arr[1] == *(ptr+1);
Multidimensional arrays
It is possible to create a multidimensional array for example if you wished to represent a matrix of constants or you wanted to store the x,y,z coordinates of a particle in an array. They are declared by creating putting two pairs of[]in the declaration.
An example of creating a 2 dimensional 3x3 array is shown below
int arr[3][3] = {{1,2,3},{4,5,6},{7,8,9}};
It is also possible to create higher dimensional arrays for example, the following creates a 3 dimensional array:
int arr[3][3][3] = {{{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}}};
Accessing an element in a multidimensional array
The elements in a multidimensional array are accessed by chaining subscript operators:int arr[3][3] = {{1,2,3},{4,5,6},{7,8,9}}; printf("a_22=%i\n", arr[2][2]);This example gets the 3rd element from the 3rd row and would produce 9.