🏠Arrays in C: Your Data’s Apartment Building
Imagine you’re building a tiny village. Instead of giving each person their own random house scattered everywhere, you build an apartment building—a row of numbered rooms, all next to each other. That’s exactly what an array is in C!
🎯 What is an Array?
An array is like a row of mailboxes at an apartment building.
- All mailboxes are the same size (same data type)
- Each has a number (index) starting from 0
- They’re all next to each other in memory
int scores[5];
// 5 mailboxes, numbered 0, 1, 2, 3, 4
📦 One-Dimensional Arrays
A one-dimensional array is the simplest kind—just a single row of boxes.
Real Life Example:
- A row of 7 chairs for 7 friends
- A week has 7 days:
days[0]todays[6]
graph TD A["Array: scores"] --> B["[0] = 85"] A --> C["[1] = 90"] A --> D["[2] = 78"] A --> E["[3] = 92"] A --> F["[4] = 88"]
📝 Array Declaration
Declaring an array is like telling the builder: “I need 5 rooms of this size.”
Syntax
dataType arrayName[size];
Examples
int ages[4]; // 4 integers
float prices[10]; // 10 decimals
char name[20]; // 20 characters
With Initial Values
You can move people in right away!
int scores[5] = {85, 90, 78, 92, 88};
Shortcut: Let C count for you:
int scores[] = {85, 90, 78, 92, 88};
// C figures out: size = 5
Partial fill: Empty rooms get zero:
int nums[5] = {1, 2};
// Result: {1, 2, 0, 0, 0}
🔢 Array Indexing and Traversal
Indexing: Finding the Right Room
Every room has a number starting from 0 (not 1!).
int scores[5] = {85, 90, 78, 92, 88};
scores[0] // First item → 85
scores[2] // Third item → 78
scores[4] // Last item → 88
Think of it like this:
scores[0]= Ground floor (index 0)scores[1]= 1st floorscores[4]= 4th floor (the top!)
Changing a Value
scores[2] = 100; // Room 2 now has 100
Traversal: Visiting Every Room
To visit every room, use a loop!
int scores[5] = {85, 90, 78, 92, 88};
for (int i = 0; i < 5; i++) {
printf("Score %d: %d\n", i, scores[i]);
}
Output:
Score 0: 85
Score 1: 90
Score 2: 78
Score 3: 92
Score 4: 88
⚠️ Array Bounds and Safety
The Danger Zone
Arrays don’t have guards! If you try to enter room 10 in a 5-room building… bad things happen.
int nums[5] = {1, 2, 3, 4, 5};
nums[5] = 99; // 🚨 DANGER! Room 5 doesn't exist!
nums[-1] = 0; // 🚨 DANGER! Negative rooms?!
What Goes Wrong?
- Undefined behavior — your program might crash
- Memory corruption — you overwrite other data
- Security bugs — hackers love this!
Stay Safe: Golden Rules
| ✅ Do This | ❌ Avoid This |
|---|---|
| Check index < size | Assume all indices are safe |
Use loops with i < n |
Use i <= n (off by one!) |
| Initialize arrays | Leave garbage values |
Safe Loop Pattern:
int n = 5;
int arr[5];
for (int i = 0; i < n; i++) { // âś… Safe
arr[i] = i * 10;
}
🏢 Multi-Dimensional Arrays
What if you need a grid instead of a row? Like a chessboard or a spreadsheet?
That’s a multi-dimensional array—arrays inside arrays!
graph TD A["2D Array: grid[3][4]"] --> B["Row 0: 4 columns"] A --> C["Row 1: 4 columns"] A --> D["Row 2: 4 columns"]
📊 Two-Dimensional Arrays
A 2D array is like a table with rows and columns.
Declaration
int grid[3][4];
// 3 rows, 4 columns = 12 boxes total
With Values
int matrix[2][3] = {
{1, 2, 3}, // Row 0
{4, 5, 6} // Row 1
};
Accessing Elements
matrix[0][0] // Row 0, Col 0 → 1
matrix[1][2] // Row 1, Col 2 → 6
Visual:
Col 0 Col 1 Col 2
Row 0 [ 1 , 2 , 3 ]
Row 1 [ 4 , 5 , 6 ]
Traversing a 2D Array
Use nested loops—one for rows, one for columns:
int grid[2][3] = {{1,2,3}, {4,5,6}};
for (int row = 0; row < 2; row++) {
for (int col = 0; col < 3; col++) {
printf("%d ", grid[row][col]);
}
printf("\n");
}
Output:
1 2 3
4 5 6
🎠Array Decay: The Shapeshifter
Here’s a sneaky secret about arrays in C:
When you use an array’s name alone, it transforms into a pointer to its first element!
This is called array decay.
Example
int nums[5] = {10, 20, 30, 40, 50};
int *ptr = nums; // nums "decays" to &nums[0]
printf("%d\n", *ptr); // 10 (first element)
printf("%d\n", nums[0]); // 10 (same thing!)
When Does Decay Happen?
| Situation | What Happens |
|---|---|
| Pass array to function | Decays to pointer |
| Assign to pointer | Decays to pointer |
Use sizeof(array) |
⚡ NO decay! |
The sizeof Exception
int arr[5];
printf("%zu\n", sizeof(arr)); // 20 bytes (5 Ă— 4)
printf("%zu\n", sizeof(&arr[0])); // 8 bytes (pointer)
Why Care About Decay?
When you pass an array to a function, it becomes a pointer—so the function can’t know the size!
void printSize(int arr[]) {
// sizeof(arr) gives pointer size, NOT array size!
// You must pass size separately
}
int main() {
int nums[5] = {1, 2, 3, 4, 5};
printSize(nums); // Array decays here!
}
Fix: Always pass the size too:
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
}
đź§ Quick Recap
| Concept | Key Point |
|---|---|
| Array | Fixed-size container of same-type elements |
| Declaration | int arr[5]; or int arr[] = {1,2,3}; |
| Indexing | Starts at 0! arr[0] is first |
| Bounds | Stay within 0 to size-1 |
| 2D Array | arr[rows][cols] = table/grid |
| Decay | Array name → pointer to first element |
🚀 You Did It!
You now understand arrays like a pro!
Think of arrays as your organized storage system:
- Need one row of items? → 1D array
- Need a table or grid? → 2D array
- Passing to functions? → Remember decay!
Keep practicing, and arrays will feel as natural as counting! 🎉