The Analogy: A Row of Numbered Pigeonholes
An array is a row of identical pigeonholes bolted to a wall. Three things follow from that picture, and all of C's array behaviour comes out of them.
The row has a fixed number of holes. You decide the count when you build the wall, and it never changes afterwards. There is no "add one more slot" in C.
The holes are numbered from zero. The first hole is 0, and a row of five ends at 4. This is not an arbitrary quirk: the index is a distance from the start, and the first item is zero steps away.
Nobody is standing guard. If you reach for hole number 7 in a row of five, C does not stop you. Your hand goes into the wall past the last hole and grabs whatever is there — someone else's variable, part of the bookkeeping, or nothing meaningful. The program often keeps running as though everything is fine. That missing guard is the single most important fact about arrays in C.
Syntax or Core Structure
#include <stdio.h>
int main(void) {
int scores[5] = { 88, 92, 79, 95, 61 };
size_t n = sizeof scores / sizeof scores[0]; /* 5, computed by the compiler */
int total = 0;
for (size_t i = 0; i < n; i++) {
printf("scores[%zu] = %d\n", i, scores[i]);
total += scores[i];
}
printf("count = %zu, total = %d, mean = %.1f\n", n, total, (double)total / n);
return 0;
}
Output:
scores[0] = 88
scores[1] = 92
scores[2] = 79
scores[3] = 95
scores[4] = 61
count = 5, total = 415, mean = 83.0
Three idioms in that short program are worth stealing permanently. sizeof scores / sizeof scores[0] asks the compiler for the element count instead of repeating the literal 5. The loop runs i < n, never i <= n, which is what keeps the last index at 4. And (double)total / n casts before dividing, because 415 / 5 in integers would have silently truncated a non-round mean.
The initialisation forms
| Written as | Element count | Contents |
|---|---|---|
int a[5] = { 1, 2, 3, 4, 5 }; | 5 | exactly as listed |
int a[] = { 1, 2, 3 }; | 3 | the compiler counts for you |
int a[5] = { 1, 2 }; | 5 | 1, 2, then zeros |
int a[5] = { 0 }; | 5 | all zeros — the idiomatic clear |
int a[5]; | 5 | indeterminate, all five |
int a[5] = { [4] = 9 }; | 5 | zeros, then 9 (C99 designated initialiser) |
The gap between the last two rows causes real bugs. Supplying even one initialiser zero-fills the rest; supplying none leaves every element holding whatever bytes were already in that memory.
Technical Depth: An Array Is Not a Pointer
They are related but genuinely different types, and every confusing array error traces back to this distinction.
int a[5] | int *p | |
|---|---|---|
| What it is | 5 contiguous ints | one address |
sizeof | 20 on a typical build (5 x 4) | 8 on a 64-bit build |
| Can be reassigned | no — a = something will not compile | yes |
| Owns storage | yes | no, it points at someone else's |
Where they blur is at a function call. When you pass an array, the compiler converts it to a pointer to the first element — array decay — and the length is lost on the way through:
void wrong(int a[]) {
/* sizeof a is the size of a POINTER here, not of the caller's array. */
printf("%zu\n", sizeof a / sizeof a[0]); /* prints 2, or 1, never 5 */
}
void right(const int *a, size_t n) { /* the honest signature */
for (size_t i = 0; i < n; i++) printf("%d ", a[i]);
}
int a[] in a parameter list is a lie the language permits: it means int *a. So the length has to travel as its own parameter — that is why every array-taking function in the standard library, from memcpy to fwrite, takes a count.
Marking the parameter const int * is worth the four characters. It documents that the function only reads, and the compiler enforces it.
Nobody checks your index
int a[5] = { 0 };
a[5] = 99; /* one past the end: undefined behaviour */
a[-1] = 99; /* also undefined */
Neither line is a compile error, and neither reliably crashes. a[5] = 99 writes four bytes into whatever variable the compiler happened to place next, so the symptom shows up somewhere else entirely, minutes later, in code that is correct. This is why the bug is so expensive: the crash site and the cause are unrelated.
Two tools turn this from a mystery into a message. Build with -fsanitize=address -g during development and an out-of-range access reports the exact line, the array, and how far past the end you went. And -Wall -Wextra catches the subset the compiler can see statically, such as a constant index that is obviously too large.
Arrays do not assign or compare
int a[3] = { 1, 2, 3 };
int b[3];
/* b = a; does not compile */
/* if (a == b) ... compiles, but compares two ADDRESSES, never contents */
memcpy(b, a, sizeof a); /* copy */
int same = memcmp(a, b, sizeof a) == 0; /* compare contents */
a == b compiling is the trap: both operands decay to pointers, so the comparison is well-formed and always false for two distinct arrays. Use memcmp for raw bytes, or a loop when the elements need real comparison logic.
Real World Example: A Week of Sales, Summarised and Charted
This is the shape of a hundred real reporting jobs: read a fixed-size row of numbers, aggregate them in one pass, and render something a human can read at a glance.
#include <stdio.h>
#define DAYS 7 /* one source of truth for the size */
int main(void) {
const char *labels[DAYS] = { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" };
int sales[DAYS] = { 120, 95, 143, 87, 160, 210, 175 };
int total = 0;
size_t best = 0; /* index of the largest, not the value */
for (size_t i = 0; i < DAYS; i++) {
total += sales[i];
if (sales[i] > sales[best]) best = i;
printf("%-4s %4d ", labels[i], sales[i]);
for (int bar = 0; bar < sales[i] / 20; bar++) putchar('#');
putchar('\n');
}
printf("\ntotal %d mean %.1f best %s (%d)\n",
total, (double)total / DAYS, labels[best], sales[best]);
return 0;
}
Output:
Mon 120 ######
Tue 95 ####
Wed 143 #######
Thu 87 ####
Fri 160 ########
Sat 210 ##########
Sun 175 ########
total 990 mean 141.4 best Sat (210)
Each bar is one # per 20 units of sales, so 120 draws six and 95 draws four — integer division does the bucketing for free.
Three design decisions here are the transferable part. #define DAYS 7 appears once, and both arrays plus the loop bound and the mean all derive from it, so changing to a fortnight is a one-line edit that cannot leave the arrays out of step. The loop does a single pass and computes the total and the maximum together, rather than scanning three times. And best stores the index, not the value, which is what lets the final line print the label as well as the number — a running-maximum that keeps only the value throws away the information you actually wanted.
Note that best starts at 0 and the comparison is >, so ties keep the earliest day. Starting from a sentinel like INT_MIN would work too, but starting from a real element is safer: it cannot be wrong for any input, whereas a sentinel has to be chosen with the value range in mind.
Common Mistakes
- Looping to
<= n.for (int i = 0; i <= 5; i++) a[i] = 0;onint a[5]writes one element past the end. Half-open bounds —i < n— make the off-by-one impossible.
- Calling
sizeofon a parameter. Insidevoid f(int a[]),sizeof ais the size of a pointer. The idiom only works where the array was declared.
- Assuming an out-of-range access will crash. It usually does not. It corrupts an unrelated variable and the program fails later, somewhere innocent. Treat a mysterious wrong value as a possible overrun.
- Forgetting that
int a[5];is not zeroed. Accumulating into an uninitialisedtotalor scanning an uninitialised array gives garbage that changes between runs and between build flags.
- Assigning or comparing arrays directly.
b = afails to compile;a == bcompiles and compares addresses. Usememcpyandmemcmp.
- Returning a local array from a function. The array's storage dies with the function, so the returned pointer dangles. Fill a caller-supplied buffer instead.
- Mixing
intandsize_tindices.for (int i = 0; i < n; i++)withsize_t nwarns under-Wextrabecause the signediis converted, and it genuinely breaks on a countdown loop whereiwould need to go negative.
- Duplicating the size as a literal.
int a[10];in one place andi < 10in three others. The day the 10 becomes 12, one of the four gets missed. Name it with a#defineor derive it withsizeof.
Best Practices
- Derive the element count with
sizeof arr / sizeof arr[0]at the point of declaration, and pass it onward. Never re-type the literal.
- Give every array-taking function an explicit length parameter, and put it right after the pointer so the pair reads as one unit.
- Mark parameters the function only reads as
const int *. It documents intent and the compiler holds you to it.
- Initialise with
= { 0 }unless you are about to fill every element immediately. Zeroed garbage is still wrong, but it is reproducibly wrong.
- Use half-open loop bounds — start at 0, stop at
< n. Every other convention invites the off-by-one back in.
- Use
size_tfor indices and lengths, and print them with%zu.
- Keep one named constant for the size, either a
#defineor anenum, and let the declarations and loops derive from it.
- Build with
-Wall -Wextra -fsanitize=address -gwhile developing. The sanitiser turns a silent overrun into a precise report with a line number.
Practice Exercises
- One pass, four answers. Write a program with
int readings[] = { 18, 24, 9, 31, 27, 12, 24 };that computes, in a single loop, the total, the mean as adouble, the maximum, and the index of the maximum. Derive the element count withsizeof, then add an eighth reading and confirm that nothing else in the program needed editing.
- Watch the guard fail, then install one. Declare
int a[5] = { 0 };and deliberately writea[5] = 12345;, then print a neighbouring variable declared just after the array. Run it as a normal build and record what you see. Rebuild with-fsanitize=address -g, record the report, and write down the array name, the line, and how many bytes past the end the sanitiser says you went.
- Prove the decay. Write
void show(const int *a, size_t n)that prints every element, and a second versionvoid broken(int a[])that tries to compute its own length withsizeof a / sizeof a[0]and print that many. Call both with a 6-element array, record whatbrokenprints, and explain in one sentence why the number it prints is the one it is.