Arrays
suggest changeAn array is an ordered sequence of objects of one element type. Its elements are stored contiguously and have no padding between them. Arrays can contain other arrays, which is how C represents multidimensional arrays.
int values[10] = {0}; /* Ten elements, all initialized to zero. */
int numbers[] = {4, 2, 3}; /* The inferred length is three. */
values[2] = 42;
int value = values[2];
An array bound must be positive when an object with that array type is created. A variable-length array, introduced in C99, can use a run-time bound. VLA support is optional in some post-C99 language versions, so check the target implementation before relying on it.
Array-to-pointer conversion
In most expressions, an array expression is converted to a pointer to its first element. Important exceptions include an array used as:
- the operand of
sizeof; - the operand of unary
&; - a string literal that initializes a character array;
- an operand in several C23-only contexts, including
typeofandtypeof_unqual.
For an array arr, the expression arr[index] is defined in terms of *(arr + index). The index must select an element of the array; merely forming or dereferencing a pointer outside the permitted bounds can produce undefined behavior.
arr after conversion has type “pointer to element.” In contrast, &arr points to the complete array. If arr has type T[N], then &arr has type T (*)[N]. Both addresses usually have the same representation, but pointer arithmetic advances by sizeof(T) for the former and by sizeof(T[N]) for the latter.
Array parameters
An array parameter is adjusted to a pointer parameter:
void process(int values[], size_t count);
void process(int *values, size_t count);
These declarations describe the same function type. The function receives no array-length information automatically, so pass the element count separately.
C99 also permits a minimum bound in a parameter declaration:
void process(size_t count, int values[static count]);
Each call must then provide access to at least count elements. Violating that requirement causes undefined behavior; the declaration does not perform a run-time bounds check.
Length of an actual array
Within the scope where arr is an array, its element count can be calculated as:
size_t count = sizeof arr / sizeof arr[0];
This expression does not work after the array has been converted to a pointer, including inside a function that declares an array-shaped parameter.