Arrays

Location
  1. Courses

    /

  2. Quick C course

    /

  3. Arrays

Too many variables

When we need a great amount of variables, like 100, it would be very inconvenient to define all of them individually...

Defining an array

An array is a group of variables defined under a common name. We define an array like we would for a normal variable, but we add the number of variables we want, inside brackets, after its name.

We define an array of 10 variables (Called elements) of type 'float':

float array[10];

Accessing the elements of an array

We access each individual element using its index (position) within the array. The index of the first one is zero.

We assign the value 7 to the first element of the array defined above:

array[0] = 7;

And 3 to the last one:

array[9] = 3;

Specifying the values at the definition

When we define an array, we can specify the values that its elements must have, like such:

int array[4] = {1, 2, 3, 4};

Above, the first element equals 1 and the last one 4.

In that case, specifying the size of the array is optional:

int array[] = {1, 2, 3, 4};

Multidimensional arrays

It is possible to define multidimensional arrays. They work similarly to arrays with a single dimension.

We define a 2D array:

int array[2][2];

The first element:

array[0][0] = 4;

The last one:

array[1][1] = 4;

We can also define 3D arrays and so on...

int array[2][2][2];

Limits

The kind of arrays presented above are said to be 'statically allocated'. Basically, they are fast, but there is a limit to the amount of memory they can take (An array of 1000000 elements of type int may be too much). If the limit is surpassed, the program will crash.

Later, we will learn 'dynamic memory allocation' to create arrays that do not have that limitation.

Pointers

The value of an array is the address of its first element.

Let us define an array:

float array[5];

We define a pointer pointing to the first element of the array:

float *ptr = array;

Note that the line above is equivalent to:

float *ptr = &array[0];

We can access the elements of the array, through the pointer, the same way as if it was the array:

ptr[4] = 6;

Comparing arrays

We can not compare two arrays like such:

if(array1 == array2) {}

The reason is that the value of an array is the address of its first element. If we want to compare two arrays, we must compare each of its elements individually:

main.c

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
int main() { int array[5] = {1, 2, 3, 4, 5}; int array2[5] = {1, 2, 8, 4, 5}; int equal = 1; // We firt assume they are equal. // For each element. for(unsigned c=0; c < 5; c++) { if(array[c] != array[c2]) // If an element is different. { // Then the arrays are not equal. equal = 0; // We leave the loop 'for'. break; } } // Here, if 'equal' equals 1, both arrays are equal. Otherwise, they are not. return 0; }

Note that the instruction 'break;' simply makes the program leave the current loop.