C Programming • C17 baseline, standards-specific features labeled
Arrays and Bounds in C
Work with contiguous elements while carrying the array length alongside the pointer or array.
An array has a fixed number of elements, and valid indices range from zero through length minus one. C does not check those bounds for you. A function receiving an array parameter cannot discover its length from that parameter, so pass the length explicitly.
Example
#include <stddef.h>
int sum_values(const int values[], size_t length) {
int sum = 0;
for (size_t i = 0; i < length; ++i) {
sum += values[i];
}
return sum;
}
What to expect
Call sum_values(values, sizeof values / sizeof values[0]) when values is an array in the calling scope.
Key idea: Treat the pointer and its length as a pair, and never index outside the documented range.