Array bounds define the valid index range of an array. For an array containing n elements, valid indices range from 0 to n - 1.
#include <stdio.h>
int main(void)
{
int numbers[5] = {10, 20, 30, 40, 50};
for (int i = 0; i < 5; i++)
{
printf("numbers[%d] = %d\n", i, numbers[i]);
}
return 0;
}
Example Output #
numbers[0] = 10
numbers[1] = 20
numbers[2] = 30
numbers[3] = 40
numbers[4] = 50
Explanation #
The declaration:
int numbers[5] = {10, 20, 30, 40, 50};
creates an array with five elements. Its valid indices are 0, 1, 2, 3, and 4.
The loop condition:
i < 5
ensures that the index remains within the valid range.
Valid and Invalid Array Indices #
| Array declaration | Valid indices | Invalid examples |
|---|---|---|
int a[3]; |
0 to 2 |
-1, 3 |
int a[5]; |
0 to 4 |
-1, 5 |
char text[10]; |
0 to 9 |
-1, 10 |
C does not automatically check array indices at runtime. An expression such as numbers[5] accesses beyond the array’s bounds and causes undefined behavior.
For an array whose size is known at the point of declaration, a loop can use the element count to avoid hardcoding the bound:
size_t count = sizeof(numbers) / sizeof(numbers[0]);
for (size_t i = 0; i < count; i++)
{
printf("%d\n", numbers[i]);
}
This calculation works here because numbers is an actual array, not a pointer parameter.