Skip to content

Arrays#

An array in the C programming language is a sequence of values of the same data type.

The syntax for declaring an array is the following:

data-type array-name[array-length];
  • The data-type is the data type of the elements in the sequence.
  • The array-name is the name of the sequence.
  • The array-length is the total number of elements in the sequence.

To access an element in the array, we use the following syntax:

array-name[index]

Here, index is the index of the element (starting at \(0\)) which we want to access. Trying to access an element at an index >= array-length is undefined behavior.

Decay#

Arrays are very similar to pointers which allows for an implicit conversion of the former to the latter. Specifically, converting an array of elements of a specific data type returns the address of the first element in the array as a pointer to the data type. This process is known as array decay because the information about the size of the array is lost.

Most commonly, decay happens when trying to pass an array to a function, which is impossible to do directly. The syntax data-type array-name[] as a parameter declaration in a function is just syntactic sugar for data-type *array-name. This means that you can only pass a pointer to the first element in the array.