eolas/zk/Arrays_in_C.md
2025-12-15 17:26:02 +00:00

833 B

tags
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:

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:

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.