An array is a tool that handles values of the same data type as a bundle. Instead of creating 100 separate variables, you can process them as one 100-space array.
Learning Objectives
- Declare, initialize, and index the 1-dimensional/2-dimensional array.
- Find the array length using the
sizeoftrick. - Understand through pictures how the array is arranged in memory.
- Know the risk of index range errors.
Why do you need an array?
If we treat the scores of 5 students as 5 variables:
int s1=90, s2=85, s3=78, s4=92, s5=88; //The same process must be repeated 5 times
Converting it to an array:
int score[5] = {90, 85, 78, 92, 88};
for (int i = 0; i < 5; i++) printf("%d\n", score[i]);
Even if the number of students increases to 100, the code remains virtually the same.
Key concepts
1) Declaration and initialization
int a[5]; //garbage price
int b[5] = {1, 2, 3}; //Fill the rest with 0
int c[] = {10, 20, 30}; //Size determined by compiler (3)
2) Arrays in memory are “contiguous columns”
int arr[5] = {10, 20, 30, 40, 50};
Address: 0x100 0x104 0x108 0x10c 0x110
┌─────┬─────┬─────┬─────┬─────┐
│ 10 │ 20 │ 30 │ 40 │ 50 │
└─────┴─────┴─────┴─────┴─────┘
Index: [0] [1] [2] [3] [4]
Each cell is spaced sizeof(int) bytes apart.
Index starts from 0. The last index is Length - 1.
3) Calculate length — sizeof trick
int arr[10];
size_t n = sizeof(arr) / sizeof(arr[0]); // 10
Divide the total number of bytes by the number of bytes per space. Caution: This does not work with arrays received as function parameters (they are converted to pointers and size information is lost).
4) Two-dimensional array (matrix)
int grid[3][4]; //3 rows 4 columns
grid[i][j] = i * 4 + j;
grid[0]: ┌────┬────┬────┬────┐
│ 0 │ 1 │ 2 │ 3 │
grid[1]: ├────┼────┼────┼────┤
│ 4 │ 5 │ 6 │ 7 │
grid[2]: ├────┼────┼────┼────┤
│ 8 │ 9 │ 10 │ 11 │
└────┴────┴────┴────┘
C stores things in memory row-major (one line must end before the next).
See as example
Example 1 — ex01_basic.c: Input and Output
int arr[5];
for (int i = 0; i < 5; i++) scanf("%d", &arr[i]);
for (int i = 0; i < 5; i++) printf("%d ", arr[i]);
Input: 10 20 30 40 50
arr[0] input: arr[1] input: arr[2] input: arr[3] input: arr[4] input: input value: 10 20 30 40 50
Key point: Like &arr[i], we pass addresses of individual elements to scanf.
Example 2 — ex02_max.c: Finding the maximum value
int max = arr[0];
for (size_t i = 1; i < n; i++)
if (arr[i] > max) max = arr[i];
Execution result
Maximum: 56 (index 5)
Key point: “Take the first element as a temporary answer and compare the rest” is the standard pattern.
Example 3 — ex03_reverse.c: Flipping an array
for (size_t i = 0; i < n / 2; i++) {
int t = arr[i];
arr[i] = arr[n - 1 - i];
arr[n - 1 - i] = t;
}
Execution result
Flipped result: 7 6 5 4 3 2 1
Key point: swap inwards from both ends. n/2 repetitions are sufficient.
Example 4 — ex04_2d.c: Two-dimensional array sum
int A[2][3] = {{1, 2, 3}, {4, 5, 6}};
int B[2][3] = {{6, 5, 4}, {3, 2, 1}};
for (i...) for (j...) C[i][j] = A[i][j] + B[i][j];
Execution result
A + B =
7 7 7
7 7 7
Key point: traversing a matrix with a double for. Don't forget \n in each line when printing.
A different perspective — arr[i] is actually *(arr + i)
In C grammar, arr[i] is automatically converted to *(arr + i) by the compiler.
That is, the array name behaves like the address of the first element (see the Pointers section for more information).
arr ─► ┌────┬────┬────┬────┬────┐
│ 10 │ 20 │ 30 │ 40 │ 50 │
└────┴────┴────┴────┴────┘
i=0 i=1 i=2 ...
arr + 2 ──────────► (This address is the address of arr[2])
Common Mistakes
- Index Overrun:
int a[5]; a[5] = 0;→ Undefined operation. - Loop condition inequality mistake: Approach one more space with
for (i = 0; i <= n; i++). sizeof(arr) / sizeof(arr[0])in the function: always becomespointer/elementin the parameter, which is broken.- 2D array row/column confusion: In
arr[i][j],iis the row,jis the column. - Depends on Variable Length Array (VLA):
int a[n];is possible with C99 variable array, but large n risks stack overflow.
Cleanup
- An array is a group of values of the same data type placed consecutively in memory.
- The index starts from 0, and the last one is
Length - 1. sizeof(arr) / sizeof(arr[0])is only valid for local arrays.- Two-dimensional arrays are accessed in
[row][column]order and stored in row priority. - Since the compiler does not check the index range, the developer is responsible.
Try it yourself
cd src
gcc -std=c11 -Wall -o ex01 ex01_basic.c && echo "10 20 30 40 50" | ./ex01
gcc -std=c11 -Wall -o ex02 ex02_max.c && ./ex02
gcc -std=c11 -Wall -o ex03 ex03_reverse.c && ./ex03
gcc -std=c11 -Wall -o ex04 ex04_2d.c && ./ex04
Application:
- Try extending it to also find the minimum in
ex02. - Try changing
ex04to a 5x5 matrix and output the identity matrix (1 on the diagonal only).