Nearby lessons
54 of 124C - Array Initialization
Every way to initialise an array in C — full lists, partial lists, letting the compiler count the size, zeroing an array with {0}, designated initialisers, and assigning element by element.
Full Initialisation
List every value inside braces, separated by commas. The count must not exceed the declared size:
Partial Initialisation — The Rest Become 0
If you supply fewer values than the size, C fills the remainder with zero. This is guaranteed by the standard, not luck:
Let the Compiler Count
Leave the brackets empty and the compiler sizes the array from the list. Now adding a value cannot desynchronise the size:
Zeroing an Entire Array
The idiom {0} sets the first element to 0 and — by the partial-initialisation rule — every other element to 0 as well:
Designated Initialisers (C99)
You can name the index you want to set. Everything you skip becomes 0 — very handy for sparse arrays:
Initialising After Declaration
The brace list only works at the moment of declaration. Later on you must assign element by element, usually in a loop:
Filling an Array from User Input
The most common real pattern: declare, then fill with a loop and scanf:
Common Mistakes
| Mistake | Why it fails |
|---|---|
int a[3] = {1,2,3,4}; | Too many initialisers — compiler error |
int a[]; | No size and no list — compiler cannot size it |
a = {1,2,3}; after declaring | Arrays are not assignable |
b = a; to copy an array | Not allowed — copy with a loop or memcpy |
if (a == b) to compare | Compares addresses, not contents |
int a[100] = {1}; does not fill the array with 1. It sets a[0] = 1 and the other 99 elements to 0. Only {0} does what people expect, because the fill value happens to be 0 too.- int a[5] = {1,2,3,4,5}; initialises all elements.
- Missing values are filled with 0 automatically.
- int a[] = {1,2,3}; lets the compiler count — size becomes 3.
- int a[100] = {0}; zeroes the whole array.
- An array cannot be assigned with = after declaration.