Arrays
An array is a sequence of same-type values that are consecutive in memory.
Declaring an Array
To declare an array, specify its type and size (the number of items in the sequence). For example, an array of 4 integers can be declared as follows:
int myArray[4];
A few variations on this declaration are:
int myArray[4] = {42, 45, 65, -5}; // initializes the values in the array
int myArray[4] = {0}; // initializes all the values in the array to 0
int myArray[] = {42, 45, 65, -5}; // initializes the values in the array, compiler intuits the array size
Accessing an Array
To refer to an element, one must specify the array name (for example, my_array
) and the position number (for example, 0
):
int my_array[5];
my_array[0] = 8;
printf("I just initialized the element at index 0 to %d!\n", my_array[0]);
After which the array would look like this in memory (where larger addresses are higher on the screen):
To sum the elements of an array, we might write code like this:
int sum_array(int *array, int n) {
int sum = 0;
for (int i = 0; i < n; ++i) {
answer += array[i];
}
return sum;
}
int main() {
int data[4] = {4, 6, 3, 8};
int sum = sum_array(data, 4);
printf("sum: %d\n", sum);
return 0;
}
Accessing an Array using Pointer Arithmetic
In C, you can treat arrays as pointers: namely, to the first element in the sequence.
This means that, perhaps surprisingly, the syntax array[i]
is shorthand for *(array + i)
:
that is, a combination of pointer arithmetic and dereferencing.
So you can think of array[i]
as treating array
as a pointer to the first element, then shifting the pointer over by i
slots, and then dereferencing the pointer to that shifted location.
Passing Arrays as Parameters
You can also treat arrays as pointers when you pass them into functions. You already saw this above; we declared a function this way:
int sum_array(int *array, int n) { ... }
and then called it like sum_array(data, 4)
.
Even though we declared data
as an array, C lets you treat it as a pointer to the first element.
It’s usually a good idea to pass around the length of the array in a separate parameter so you know how big the array is!
Common Pitfalls
- C has no array-bound checks. You won’t even get a warning! If you write past the end of an array, you will simply start overwriting the values of other data in memory.
sizeof(array)
will return a different value based on how the variablearray
was declared. Ifarray
is declared asint *array
, thenarray
will be considered the size of a pointer. If it was declared asint array[100]
then it will be considered the size of 100int
s.
Multidimensional Arrays
C lets you declare multidimensional arrays, like int matrix[4][3]
.
However, it still lays everything out sequentially in memory.
Here’s a visualization of what that matrix looks like conceptually and in memory:
This array occupies (4 * 3 * sizeof(double))
bytes of memory.