An array’s elements need values before they are used. C lets you give all of them at once in the declaration. This section covers the initialisation rules, what uninitialised elements hold, and how subscripts select elements, including what goes wrong when a subscript is out of range.
The partial-initialisation rule gives an easy way to clear a whole array: = {0}.
What an array holds when it is not initialised depends on where it is declared:
Kind of array
Initial contents
Local (inside a function), no initialiser
Indeterminate (“garbage”) values
Global or static, no initialiser
All zeros
Any array with a partial initialiser
Listed values, then zeros
An array cannot be assigned as a whole after its declaration: a = {1, 2, 3}; and a = b; are errors. Assign element by element, usually in a loop.
Character array initialisation
A character array can be initialised with a string constant, which adds the null character '\0' at the end:
Declaration
Size
Contents
A string?
char t[] = "TIN";
4
'T' 'I' 'N' '\0'
Yes
char t[4] = "TIN";
4
'T' 'I' 'N' '\0'
Yes
char t[3] = "TIN";
3
'T' 'I' 'N'
No: no room for '\0'
char t[] = {'T', 'I', 'N'};
3
'T' 'I' 'N'
No
Strings are covered fully later in this unit.
Subscripts
A subscript may be a constant, a variable or any integer expression: a[3], a[i], a[i + 1], a[2 * k].
Out-of-range subscripts
C does not check subscripts when the program runs. Using an index outside 0 to size − 1 is undefined behaviour: the program may read garbage, overwrite another variable, crash, or appear to work. This is the most common source of serious bugs in C programs.
Key takeaways
type a[n] = {…}; initialises from index 0; missing values become 0; the size may be omitted.
Uninitialised local arrays hold garbage; global and static arrays hold zeros.
A string constant initialiser adds '\0', so it needs one extra element.
Subscripts run from 0 to size − 1; C does not check them.
Practice questions
Answer on paper first, then check. The explanation matters more than the letter you chose.
Question 6 · short answer
Write a loop that sets every element of int sq[10]; to the square of its index, and state the value of sq[7].
Show worked answer
for (i = 0; i < 10; i++) sq[i] = i * i;. The loop runs with i from 0 to 9, which are exactly the valid subscripts, and stores i × i in element i. Therefore sq[7] is 7 × 7 = 49.
MCA Online notes are made for reading on screen. Open https://mcastudy.online/mcs-201/arrays-and-strings/array-initialisation-and-subscripts/ to read this page.