Arrays#
An array of N T is T name[N]. Its size is part of
the type; int[3] and int[4] are different. Inside an
expression, an array name decays to a pointer to its first
element, losing the size information.
int xs[3] = {1, 2, 3};
size_t n = sizeof xs / sizeof xs[0]; /* 3 */
Decay loses size; the pointer copy has no length information.
int *p = xs; /* decay to int* */
/* sizeof p is the pointer size, not the array size */
Pass an array length alongside the pointer.
void print(const int *xs, size_t n) {
for (size_t i = 0; i < n; i++) printf("%d\n", xs[i]);
}
VLA (variable-length arrays, C99) let the operator size at runtime; C11 made them optional, and they are best avoided for portability and stack safety.