In Lesson 5 of Learn C With Me, we dive into arrays in C.
Using Beej’s Guide to C as our study material, we start with simple one-dimensional arrays and gradually work our way toward multidimensional arrays, while experimenting with the code ourselves along the way.
We cover:
- What arrays are and how to declare them
- Accessing array elements using indexes
- Why array indexes start at zero
- Iterating through arrays with
forloops - Getting the size of an array with
sizeof - Calculating the number of elements in an array
- Why the
sizeoftrick stops working when an array is passed to a function - The relationship between arrays and pointers
- Array initializers
- Partially initializing arrays
- Automatically initializing remaining elements to zero
- Initializing specific array indexes
- Letting C determine the size of an array from its initializer
- Accessing arrays out of bounds
- Undefined behavior and why the compiler might not warn you about it
- Experimenting with GCC and Clang warnings
- Multidimensional arrays
- Row-major storage
- Understanding arrays with more than two dimensions
- Nested
forloops for working with multidimensional arrays - Initializing multidimensional arrays
One of the most interesting parts of this lesson is seeing what happens when we deliberately read beyond the end of an array. The program compiles perfectly fine — but the results demonstrate one of the most important concepts to understand when programming in C: undefined behavior.
We also discover an important connection to our previous lesson on pointers: when an array is passed to a function, what the function actually receives is effectively a pointer to the first element. This explains why determining an array’s length with sizeof doesn’t work inside the called function.
As usual, this isn’t a polished programming tutorial. We’re learning C together, experimenting with the code, asking questions, making mistakes, reading the compiler output, and trying to understand why C behaves the way it does rather than simply memorizing syntax.
We stop just before Arrays and Pointers, which we’ll tackle in the next lesson.