This chapter is really a direct follow-up to pointers, and it's yet another example of how useful they are. Thought you'd escape them? No such luck!
Pointers are everywhere, I warned you.
In this chapter, we're going to learn how to create variables called arrays. Arrays are super useful in C, and they're used all the time :)
We'll start off with a few explanations about how arrays work in memory (with diagrams to help). Trust me, these little intros about memory are incredibly important — they help you really understand how things work. And let's be honest: a programmer who understands what they're doing is definitely more reassuring when it comes to program stability, right?
Arrays in Memory
"Arrays are a sequence of variables of the same type, located in a contiguous block of memory."
Okay, I'll admit — that does sound a bit like a dictionary definition.
In simpler terms, think of arrays as "big variables" that can store multiple numbers of the same type (long, int, char, double, etc.)
An array has a specific size. It can hold 2 values, 3, 4, 10, 250 — you name it.
Here's a little diagram showing a 4-element array in memory, starting at address 2500:
Address | Value |
---|---|
2500 | 10 | 2501 | 47 | 2502 | 205 | 2503 | 2 | 2504 | 70 |
When you ask to create a 5-element array in memory, your program requests permission from the OS to use 5 memory cells. These cells have to be contiguous, meaning right next to each other in memory.
As you can see, the addresses are sequential: 2500, 2501, 2502, 2503, 2504. There are no gaps.
Also, each cell in the array holds a value of the same type. If the array is of type int, then every single slot in it stores an int. You can't mix and match — no arrays with both int and double values, for example.
To sum it up, here's what you need to remember about arrays:
- When you create an array, it takes up a contiguous space in memory: all the cells are placed one after another.
- All elements in an array are of the same type. So, an int array will contain only ints — nothing else.
Defining an Array
Let's start by seeing how to define an array of 5 ints:
int array[5];
And that's it! :)
You just add the number of elements you want between the square brackets. There's no real limit — well, maybe your memory size, but that's about it :D
Now, how do we access each element of the array? You simply write array[index]
.
If I want to store the same values as the ones in the diagram earlier, I'd write:
int array[5];array[0] = 10; array[1] = 47; array[2] = 205; array[3] = 2; array[4] = 70;
Actually, if you just write array, what you're really holding is a pointer. It's a pointer to the first element of the array.
Try this out:
int array[5];printf("%d", array);
The result? You'll see the memory address where the array starts:
2500
But if you include the index in square brackets, you get the value instead:
int array[5];printf("%d", array[0]);
Output:
10
Same idea for the other indices.
And since array is a pointer, you can also use the * symbol to get the first value:
int array[5];printf("%d", *array);
Which gives:
10
You can also get the second value using *(array + 1) (that's the address of array + 1). So these two lines do the same thing:
array[1] // Returns the value in the second element (remember, the first is at index 0) *(array + 1) // Exactly the same: returns the second element's value
So when you write array[0], you're asking for the value at the address array + 0 elements (i.e. 2500). If you write array[1], you're getting the value at array + 1 (i.e. 2501). And so on for the rest :)
Dynamically Sized Arrays
The C language has multiple versions.
Starting with C99, newer versions of C allow for arrays with dynamic sizes — that is, arrays where the size is determined by a variable:
int size = 5; int array[size];
However, not all compilers support this — some will crash on line 2. The older "classic" version of C (called C89) does not allow this kind of thing.
So for now, let's just assume this is off-limits. If you really want to try it, make sure to check which version of C you're using! Also, let's agree on one rule: you're not allowed to use a variable between the square brackets, even if it's a constant! So something like const int size = 5;
won't work either.
Your array must have a fixed size written out explicitly:
int array[5];
Don't worry, it's totally possible! (Even in C89.)
But to do that, we'll need to use a different method — something safer and universally compatible — called dynamic memory allocation. We'll get into that later in Part III of this course.
Looping Through an Array
Let's say now I want to print every element of the array. Sure, I could use one printf per element. But that's repetitive, kind of tedious… and imagine the nightmare if the array had over 9000 numbers!
The better solution? A loop.
Why not a for loop? for loops are perfect for going through an array:
int main(int argc, char *argv[]) { int array[5], i = 0;array[0] = 10; array[1] = 47; array[2] = 205; array[3] = 2; array[4] = 70;
for (i = 0 ; i < 5 ; i++) { printf("%d\n", array[i]); }
return 0; }
Output:
10 47 205 2 70
Our loop runs through the array using a variable named i (which is the super original name most programmers give to loop variables :p)
One cool thing is that you can put a variable between the square brackets. Sure, you can't use variables when defining the array size, but you can absolutely use one to loop through the array — and display its values!
Here, we used i, which goes from 0 to 4. So we display the values of array[0], array[1], array[2], array[3], and array[4]! :)
- Be careful not to try printing array[5] if you only have 5 elements!
- An array with 5 elements has indices 0 through 4. Period.
- If you try to access array[5], you'll either get garbage or a nasty error — your program might crash if the OS blocks access to that memory.
So there you go — that's the trick . Not too complicated, right?
Initializing an Array
Now that we know how to loop through an array, we can easily initialize all its values to 0 using a loop!
Looping through and setting each value to 0 isn't too hard — you've got this ;)
int main(int argc, char *argv[]) { int array[4], i = 0;// Initialize the array for (i = 0 ; i < 4 ; i++) { array[i] = 0; }
// Print the values to check for (i = 0 ; i < 4 ; i++) { printf("%d\n", array[i]); }
return 0; }
Output:
0 0 0 0
Another Way to Initialize
There's another, more automatic way to initialize an array in C.
You can use this syntax: array[4] = {value1, value2, value3, value4}
Just list the values one by one, inside curly braces, separated by commas:
int main(int argc, char *argv[]) { int array[4] = {0, 0, 0, 0}, i = 0;for (i = 0 ; i < 4 ; i++) { printf("%d\n", array[i]); }
return 0; }
Output:
0 0 0 0
But here's the best part: you don't even need to fill every value manually — if you only define the first few values, the rest will automatically be set to 0!
For example:
int array[4] = {10, 23}; // Sets values: 10, 23, 0, 0
Element 0 gets 10, element 1 gets 23, and the rest are filled with 0s by default.
Simple! Just initialize the first value to 0, and the rest will follow:
int array[4] = {0}; // All elements will be set to 0
This works for arrays of any size — not just 4. Even if you had 100 elements, it would still work just fine ;)
int array[4] = {1};
does not set all the elements to 1 — only the first one. The rest will still be 0. So if you want all the values to be 1, you'll have to use a loop.Passing Arrays to a Function
You'll often need to display the contents of an entire array.
So why not write a function that does it for you? That way, we'll also learn how to pass an array to a function — so it's a win-win.
We'll need to pass two pieces of information to the function: the array (or rather, its address — it's way better performance-wise than copying the whole thing), and most importantly... its size!
Yep, the function needs to work with arrays of any size. But inside the function, you don't magically know how many elements are in the array. That's why you need to pass a variable along with it — let's call it something like arraySize
.
Like I said earlier, an array can be seen as a pointer. So, we can pass it to a function just like we'd pass a regular old pointer:
// Function prototype for displaying the array void display(int *array, int arraySize);int main(int argc, char *argv[]) { int array[5] = {10, 47, 3};
// Display the contents of the array display(array, 5);
return 0; }
void display(int *array, int arraySize) { int i;
for (i = 0; i < arraySize; i++) { printf("%d\n", array[i]); } }
Output:
10 47 3 0 0
The function itself isn't much different from what we saw back in the chapter on pointers. It takes two parameters: a pointer to an int (our array), and the size of that array (which is crucial — you need to know when to stop the loop!). Then it just prints out the contents using a good old for loop.
Tip: there's another way to declare that a function is receiving an array. Instead of saying int *array
, you can write:
void display(int array[], int arraySize)
It behaves exactly the same, but the square brackets make it clearer to the reader that the function is working with an array, not just a regular pointer. That visual cue helps avoid confusion ;)
Personally, I always use brackets in function parameters to make it obvious it's an array. I recommend you do the same. (And don't worry, this time you don't need to put the array's size inside the brackets.)
Once you've got this down, working with arrays becomes second nature... calculating the average, median, mode, sorting values in ascending or descending order — no big deal anymore!
When you understand pointers, the rest really falls into place. I doubt you found this chapter too tricky (though hey, I could be wrong ^^)
But fair warning — there are a couple of pitfalls you must watch out for. If I had to leave you with two golden rules, they'd be:
- Never ever forget that arrays start at index 0, not 1.
- When passing an array to a function, always pass its size along with it. Otherwise, there's no way to know how many elements you're working with!
Oh and hey, I've got good news: you're now ready to work with strings — a.k.a. text! That means you'll soon be able to store words in memory, and even ask the user for their name, for example :)
Took us a bit to get here, huh? Who would've thought something so "simple" like that actually needed a whole journey to understand. But here we are!
Perfect timing, too — because next up, we're diving right into character strings. Let's go!
Enjoyed this C / C++ course?
If you liked this lesson, you can find the book "Learn C Programing for Beginners" from the same authors, available on SiteRaw, in bookstores and in online libraries in either digital or paperback format. You will find a complete C / C++ workshop with many exclusive bonus chapters.