Explain it simply
Explain it simply
Picture a weekly pill box: seven compartments in one row, side by side, each holding the same kind of thing. The whole box has one name, and you pick a compartment by its number. C numbers them from 0, so the first compartment is [0].
Use an array for a known number of values of the same type: five exam scores, a price list, a week of daily temperatures. Its size is fixed when you create it and cannot grow later.
Problem → Why → Solution
The problem: C does not guard the end of an array
You loop over four scores but write i <= 4. On the fifth pass the loop reads scores[4], an element that does not exist. C does not stop you: the program may print a nonsense total, crash, or by luck appear to work. Writing past the end is worse still, because it can silently overwrite a neighbouring variable.
#include <stdio.h>
int main(void) {
int scores[4] = {80, 75, 90, 60};
int total = 0;
for (int i = 0; i <= 4; i++) { /* i == 4 is one past the end */
total += scores[i]; /* reads memory that is not scores */
}
printf("Total: %d\n", total); /* anything can happen */
return 0;
}Why doesn't the compiler stop this?
C arrays carry no length at run time and C performs no index check: scores[i] simply means "start address + i * sizeof(int)". For i == 4 that address lies past the array, and the C standard calls reading it undefined behaviour. The compiler may assume it never happens, so any result is possible. GCC at -O0 with -Wall -Wextra says nothing about this loop; only at -O2 can it warn "iteration 4 invokes undefined behavior". Do not rely on warnings: derive the bound from the array itself.
Core concept: contiguous boxes, length only in the type
An array is a fixed number of elements of one type, stored one after another in memory with no gaps. int scores[4] reserves room for exactly four ints; where int is 4 bytes, that is 16 contiguous bytes. The size is part of the array's type and cannot change after the array is created. Element i sits i element-sizes after the start, which is why indexing is fast and why the first element is number 0: it is zero steps from the start.
An initialiser fills elements in order. int a[5] = {7, 3}; sets a[0] and a[1] and fills the remaining three with 0, and int zeros[4] = {0}; is the usual way to zero a whole array. Leave the size out, as in int scores[] = {80, 75, 90, 60};, and the compiler counts the initialisers and makes the array exactly that long. A local array with no initialiser at all, int a[5];, holds indeterminate values, so reading one before writing it is a bug.
C does not store the length anywhere you can ask for it at run time, and it does not check indexes. The only length information lives in the compile-time type, and sizeof scores / sizeof scores[0] turns it into an element count: 16 bytes / 4 bytes = 4. That trick works only where the array itself is in scope. In most expressions an array name decays to a pointer to its first element, and a function that receives an array receives only that pointer. Inside the function, sizeof gives the size of a pointer (8 bytes on typical 64-bit systems), not the array. So the count must travel with the array as a separate size_t parameter.
Arrays cannot be assigned or compared as a whole: b = a; is a compile error ("assignment to expression with array type"), and a == b compares addresses, not contents. Copy and compare element by element in a loop, or use memcpy() and memcmp() from <string.h>.
int scores[4] in memory (int = 4 bytes here)
--------------------------------------------
index: [0] [1] [2] [3] | [4] ???
+--------+--------+--------+--------+-----------
value: | 80 | 75 | 90 | 60 | not yours
+--------+--------+--------+--------+-----------
offset: +0 +4 +8 +12 | +16 bytes
sizeof scores = 16 bytes count = 16 / 4 = 4
valid indexes: 0 .. count - 1 (scores[4] is undefined behaviour)- A fixed row of same-type boxes
- Box i is i steps from the start
- Valid indexes: 0 to count - 1
- Always carry the count with the array
An array knows its size only where it is declared; everywhere else, you carry the count yourself.
General pattern
type name[COUNT]; /* local, no initialiser: garbage */
type name[] = {v0, v1, v2}; /* size counted by the compiler */
type name[COUNT] = {0}; /* every element is 0 */
size_t count = sizeof name / sizeof name[0];
for (size_t i = 0; i < count; i++) {
use(name[i]);
}
result function_name(const type values[], size_t count);COUNT is a positive integer known at compile time. Compute the element count with sizeof, then loop from 0 with < count. A function that only reads the array takes a const array parameter plus the count.
Example: total and average of four scores
Notice that the number 4 is not hard-coded anywhere in the loop. The element count is computed from the array, so adding a fifth score means editing only the initialiser line.
#include <stdio.h>
int main(void) {
int scores[] = {80, 75, 90, 60};
size_t count = sizeof scores / sizeof scores[0];
int total = 0;
for (size_t i = 0; i < count; i++) {
total += scores[i];
}
printf("Count: %zu\n", count);
printf("Total: %d\n", total);
printf("Average: %.2f\n", (double)total / count);
printf("First: %d, last: %d\n", scores[0], scores[count - 1]);
return 0;
}Code breakdown
- Size from the initialiser
int scores[] = {80, 75, 90, 60};With no size in the brackets, the compiler counts the four values and creates an int[4] array.
- Element count
size_t count = sizeof scores / sizeof scores[0];sizeof scores is the whole array in bytes (16) and sizeof scores[0] is one element (4). Their quotient, 4, is correct whatever size int happens to be.
- Valid indexes only
for (size_t i = 0; i < count; i++) {i takes 0, 1, 2 and 3; at i == 4 the < stops the loop, so it never leaves the array. i has the same type as count, size_t, so there is no sign-compare warning.
- Real division
printf("Average: %.2f\n", (double)total / count);Without the (double) cast, total / count would be integer division giving 76, and the result would not even match %.2f. The cast produces 305.0 / 4 = 76.25.
- First and last
scores[0], scores[count - 1]The first element is always [0] and the last is [count - 1], never [count].
Count: 4
Total: 305
Average: 76.25
First: 80, last: 60Initialising and copying
The code below shows that missing initialisers become 0, and copies one array into another element by element. Writing copy = partial; would be a compile error, which is why the loop is needed.
#include <stdio.h>
int main(void) {
int partial[5] = {7, 3}; /* the rest become 0 */
int zeros[4] = {0}; /* every element is 0 */
int copy[5];
size_t n = sizeof partial / sizeof partial[0];
for (size_t i = 0; i < n; i++) {
copy[i] = partial[i] * 10; /* arrays are copied element by element */
}
for (size_t i = 0; i < n; i++) {
printf("%d ", partial[i]);
}
printf("| %d %d | %d\n", zeros[0], zeros[3], copy[1]);
return 0;
}Passing an array to a function
Functions get their own lesson soon, but one rule about arrays is worth knowing now. When you call sum_all(scores, count), scores decays to the address of its first element, and the function receives a pointer to the caller's data, not a copy. const int values[] promises that the function will not change the elements.
#include <stdio.h>
int sum_all(const int values[], size_t count) {
int total = 0;
for (size_t i = 0; i < count; i++) {
total += values[i];
}
return total;
}
int main(void) {
int scores[] = {80, 75, 90, 60};
size_t count = sizeof scores / sizeof scores[0];
printf("sizeof scores in main: %zu bytes\n", sizeof scores);
printf("sum: %d\n", sum_all(scores, count));
return 0;
}Writing sizeof values / sizeof values[0] inside sum_all would give 8 / 4 = 2 on a 64-bit system and add only two elements (80 + 75 = 155). GCC warns about this by default: "'sizeof' on array function parameter 'values' will return size of 'const int *'". The values[] spelling looks like an array, but the parameter's real type is const int *.
In real projects
Where this shows up in real projects
Fixed-size arrays are everywhere in C, especially where memory is tight or must be predictable. Embedded firmware keeps the last 16 sensor samples in a ring-buffer array, network code reads packets into a buffer such as char buf[1500], games keep a fixed pool of 256 particles, and lookup tables such as the number of days in each month live in const arrays.
The API convention you will meet in the C standard library and in most C codebases is "a pointer plus a count": qsort(base, count, size, compare), fwrite(ptr, size, count, file), memcpy(dest, src, bytes). Writes past the end of an array, buffer overflows, have been one of the most dangerous classes of security bug in C programs for decades. That is why teams test with edge cases such as one-element and completely full arrays, and run their tests under tools such as AddressSanitizer (-fsanitize=address in GCC and Clang), which stops the program at most out-of-bounds accesses and reports where they happened.
Common mistakes
Common mistakes
1. i <= count instead of i < count
This is the bug from the problem section: the last pass touches array[count], which is undefined behaviour. Write every index loop as i = 0; i < count.
2. Using sizeof on a function parameter
An int values[] parameter is really an int *, so sizeof values gives the size of a pointer. Never compute the count with sizeof inside the function; let the caller compute it and pass it as a size_t count parameter.
3. Hard-coding the length
With for (int i = 0; i < 4; i++) and total / 4.0, adding a fifth score makes the loop silently ignore it and the average wrong; removing one makes the loop read past the end. Compute the count once from sizeof and use that variable everywhere.
4. Trying to copy an array with =
b = a; fails with "assignment to expression with array type". Copy element by element in a loop, or use memcpy(b, a, sizeof a), making sure b is at least as large as a.
Best practices
Best practices
- Compute the element count with sizeof arr / sizeof arr[0] and keep it in a size_t variable.
- Always initialise local arrays; {0} is the simplest way.
- Give every function that takes an array a count parameter, and make the array const if it is only read.
- When testing, try one element, a full array, and the boundary indexes 0 and count - 1.
Mini challenge
Mini challenge: a week of temperatures
Store a week of daily high temperatures in an array. In a single loop, find the highest and lowest temperature and count the days above 32 degrees.
- Use int temps[] = {31, 34, 29, 36, 33, 28, 35};
- Compute the number of days with sizeof instead of hard-coding 7
- Start max and min from the first element, not from 0
- Update max, min and the hot-day count inside one loop
#include <stdio.h>
int main(void) {
int temps[] = {31, 34, 29, 36, 33, 28, 35};
// TODO: compute the number of days with sizeof
// TODO: max and min start from the first element
// TODO: a counter for days above 32
// TODO: one loop over every valid index:
// update max, update min, count the hot days
// TODO: print the days, "Max: .., min: .." and the hot-day count
return 0;
}Expected: The program prints these three lines: Days: 7 Max: 36, min: 28 Days above 32: 4
Show hint
Starting max at 0 breaks for winter data where every temperature is negative, and starting min at 0 has the same problem in reverse. Starting from temps[0] is correct for any data.
Show solution
#include <stdio.h>
int main(void) {
int temps[] = {31, 34, 29, 36, 33, 28, 35};
size_t days = sizeof temps / sizeof temps[0];
int max = temps[0];
int min = temps[0];
int hot_days = 0;
for (size_t i = 0; i < days; i++) {
if (temps[i] > max) {
max = temps[i];
}
if (temps[i] < min) {
min = temps[i];
}
if (temps[i] > 32) {
hot_days++;
}
}
printf("Days: %zu\n", days);
printf("Max: %d, min: %d\n", max, min);
printf("Days above 32: %d\n", hot_days);
return 0;
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- An array stores a fixed number of same-type elements side by side, indexed from 0.
- Only indexes 0 to count - 1 are valid; anything outside is undefined behaviour that C does not check.
- sizeof arr / sizeof arr[0] gives the element count, but only in the scope where the array is declared.
- Passed to a function, an array decays to a pointer, so pass the count as a size_t parameter.
SEI CERT C Coding Standard — Carnegie Mellon SEI