C Arrays
A Row of Lockers
Imagine a hallway with a row of lockers. Each locker is the same size, each has a number painted on the door, and they sit side by side in memory. That's a C array.
When you declare an array, you're telling the compiler: "Reserve me 5 lockers in a row, all holding integers." The compiler finds a contiguous chunk of memory, slaps numbers 0 through 4 on the doors, and hands you the key to locker 0.
Declaring and Initializing
There are a few ways to create an array in C:
int scores[5];β 5 lockers, contents unknown (garbage values!)int scores[5] = {90, 85, 77, 92, 88};β 5 lockers, each filledint scores[] = {90, 85, 77, 92, 88};β compiler counts for you
The index starts at 0, not 1. So scores[0] is the first element and scores[4] is the last in a 5-element array.
Declaring and Accessing Arrays
Looping Through an Array
Arrays and loops are best friends. You almost never access each element by hand β you let a for loop walk down the hallway, opening each locker in turn.
One critical thing: C does not store the length of an array anywhere. You have to track it yourself. A common trick is sizeof(arr) / sizeof(arr[0]), but this only works when the array is in the same scope β it breaks the moment you pass the array to a function.
Filling and Printing with a Loop
scores[10] on a 5-element array, the compiler won't stop you. You'll silently read or corrupt whatever memory happens to be there. This is one of the most common sources of bugs and security vulnerabilities in C programs.Multi-Dimensional Arrays
Need a grid? A 2D array is just an array of arrays β like a spreadsheet with rows and columns. You declare it with two sets of brackets: int grid[3][4] gives you 3 rows and 4 columns.
In memory, it's still one contiguous block. Row 0 comes first, then row 1, then row 2 β all laid out flat. C is row-major.
2D Array β A Tic-Tac-Toe Grid
Passing Arrays to Functions
When you pass an array to a function, you're not passing a copy. You're passing a pointer to the first element. This means the function can modify the original array β there's no protection.
Because the size information is lost, you must pass the length as a separate argument. This is a classic C pattern you'll see everywhere.