Declaring an array with type name[size]
What you'll learn: How to reserve a block of memory to store multiple values of the same type using a single variable name.
The "Lockers" Analogy
Imagine you are a school principal. If you need to store one student’s books, you assign them a single locker. In C, this is like declaring a standard variable: int locker;.
But what if you have a team of five students? You wouldn't want to ask the janitor for five separate lockers scattered all over the building (int locker1, locker2...). Instead, you would ask for a row of five lockers right next to each other. This is exactly what an array is: a contiguous block of memory where multiple items of the same data type live side-by-side.
The Syntax
To declare an array in C, you need three specific pieces of information: the type of data you are storing, a name for the array, and the size (how many slots you need) inside square brackets.
int scores[5];
In this single line, you have told the computer:
- int: "I want to store whole numbers."
- scores: "I want to refer to this entire row of numbers by the name 'scores'."
- [5]: "I need exactly five slots reserved in memory."
Why the Size Matters
When you declare int scores[5], the C compiler goes into the computer's memory and looks for a spot big enough to fit five integers in a row. Once it finds that spot, it "bookmarks" it.
It is important to remember that in C, you must define the size of the array when you create it. Think of it like building a parking lot with concrete curbs; once you’ve built a lot for five cars, you can’t suddenly squeeze a sixth car in without starting a whole new construction project. The size you put inside the [] must be a positive whole number.
Same Type Only
Because arrays are stored as one solid block, every "slot" must be the same size. This means an array can only hold one type of data. You can have an array of float values for prices, or an array of char values for letters, but you cannot mix an int and a float in the same array.
Key takeaway
An array declaration type name[size] tells C to reserve a fixed, side-by-side sequence of memory slots for a specific data type.