42 lines
848 B
Markdown
42 lines
848 B
Markdown
|
|
---
|
||
|
|
tags:
|
||
|
|
- C
|
||
|
|
---
|
||
|
|
|
||
|
|
# Arrays in C
|
||
|
|
|
||
|
|
To declare an array in C, you must specify:
|
||
|
|
|
||
|
|
- the data type of the variables it will store
|
||
|
|
- the size (in square brackets)
|
||
|
|
- the array elements (in curly brackets)
|
||
|
|
|
||
|
|
Thus:
|
||
|
|
|
||
|
|
```c
|
||
|
|
int some_numbers[3] = {1, 2, 3};
|
||
|
|
```
|
||
|
|
|
||
|
|
> Array element individuation is the same as JavaScript, as is a standard `for`
|
||
|
|
> loop.
|
||
|
|
|
||
|
|
## Calculating the length of an array
|
||
|
|
|
||
|
|
Determining the length of an array is a fairly involved process compared to
|
||
|
|
higher-level languages. The process:
|
||
|
|
|
||
|
|
- Get the size of the array **in bytes**
|
||
|
|
- Divide this by the size of the first array element
|
||
|
|
|
||
|
|
So:
|
||
|
|
|
||
|
|
```c
|
||
|
|
int some_numbers[3] = {1, 2, 3};
|
||
|
|
int length = sizeof(some_numbers) / sizeof(arr[0]) // 3
|
||
|
|
```
|
||
|
|
|
||
|
|
What is happening under the hood:
|
||
|
|
|
||
|
|
The array has three `int` values. The normal byte size for a single `int` is 4
|
||
|
|
bytes (32 bits). 4 x 3 is 12. 12/4 is 3.
|