Array Initialization & Bounds
Initializer lists fill an array, but C will not stop you from reading past the end. Bounds are your responsibility.
In plain English
An array is a shelf with a fixed number of slots. C does not stop your hand from reaching past the last slot, so you must be careful.
Initialization and size inference
An initializer list fills elements from left to right. If you provide fewer values than the size, the remaining elements are zero-initialized. If you omit the size, the compiler infers it from the initializer list. Designated initializers such as [2] = 30 make sparse initialization explicit.
int a[5] = {10, 20, 30}; /* 10 20 30 0 0 */
int b[] = {1, 2, 3, 4}; /* size 4 */
int c[5] = {[2] = 30, [4] = 50};/* 0 0 30 0 50 */Bounds checking and undefined behaviour
C does not check array bounds at runtime. Reading or writing outside the array is undefined behaviour. It may appear to work, corrupt another variable, or crash. The rule is simple: the valid indexes are 0 through size - 1. Static analysis tools can help, but the language will not save you.
int a[3] = {1, 2, 3};
printf("%d\n", a[0]); /* valid */
printf("%d\n", a[2]); /* valid */
/* a[3] is out of bounds: undefined behaviour */Key takeaways
- Partial initialization zero-fills the remaining elements.
- Omitting the size infers it from the initializer list.
- C does not bounds-check array access.
- Valid indexes are 0 through size - 1.
Common pitfalls
- Assuming the compiler will catch an out-of-bounds index.
- Forgetting that a shorter initializer list zero-fills.
- Using a calculated index without validating it.
Key focus
- Know how partial initialization behaves.
- Expect questions on undefined behaviour from out-of-bounds access.
Quick check
1. What is the value of the last element in int a[4] = {1, 2};?
2. What happens when you access a[5] on int a[5];?