# 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;`

## 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 = 7;`

And 3 to the last one:

`array = 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 = {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;`

The first element:

`array = 4;`

The last one:

`array = 4;`

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

`int array;`

## 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;`

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;`

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

`ptr = 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

`123456789101112131415161718192021222324````int main() { int array = {1, 2, 3, 4, 5}; int array2 = {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.