2-D arrays: working with a grid · 二维数组:处理网格
A grid of boxes
- A 2-D array is a grid: rows and columns of the same type.
int g[2][3];makes 2 rows and 3 columns — 6 ints in all.- You reach one cell with two indexes:
g[row][col].
一格一格的网格
- 二维数组是一个网格:由同样类型的行和列组成。
int g[2][3];创建 2 行 3 列 —— 一共 6 个 int。- 你用两个下标访问一个格子:
g[row][col]。
Rows then columns (row-major)
- C stores a grid row by row: all of row 0, then all of row 1.
- To visit every cell, use a
forloop for the rows, and aforloop inside it for the columns. g[r][c]is the cell in rowr, columnc. Both start at0.
先行后列(行优先)
- C 把网格一行一行地存:先存完第 0 行,再存第 1 行。
- 要访问每个格子,用一个
for循环遍历行,再在里面用一个for循环遍历列。 g[r][c]是第r行、第c列的格子。两者都从0开始。
Passing a 2-D array
- When you pass a grid to a function, you must give the column count:
int g[][3]. - C needs the number of columns to find each row in memory; the row count can stay blank.
- So a function takes
int g[][3], int rows— the columns are fixed at3, the rows are passed in.
传递二维数组
- 把网格传给函数时,你必须给出列数:
int g[][3]。 - C 需要列数才能在内存里找到每一行;行数可以留空。
- 所以函数写成
int g[][3], int rows—— 列固定为3,行数则传进来。
#include <stdio.h>
int main(void) {
int g[2][3] = {{1, 2, 3}, {4, 5, 6}};
int total = 0;
for (int r = 0; r < 2; r++) {
for (int c = 0; c < 3; c++) {
total += g[r][c];
}
}
printf("%d\n", total); // 21
return 0;
}
Working one row at a time
- You can also work on a single row: loop only the columns for a fixed row
r. - This is how you sum one row, or find the biggest value in a row.
- Mixing the two — an outer row loop with an inner column loop — handles the whole grid.
一次处理一行
- 你也可以只处理一行:对固定的行
r,只循环列。 - 这就是对某一行求和、或找出某行里最大值的方法。
- 把两者结合 —— 外层循环行、内层循环列 —— 就能处理整个网格。
Common mistakes
- Index a grid
grid[row][col]. - The outer loop walks the rows, the inner loop the columns.
常见错误
- 网格索引
grid[row][col]。 - 外层循环走行,内层循环走列。
Now you try
- For the function tasks, the grid has 3 columns, so the parameter is
int g[][3]. - Do not write a
main— the checker provides one.
现在轮到你了
- 在函数任务里,网格有 3 列,所以参数是
int g[][3]。 - 不要自己写
main—— 检查器会提供。
A 2-D array is a grid · 二维数组就是网格
Reach a cell with a[row][col] — row first, then column. · 用 a[row][col] 取一个格子——先行后列。
Complete int sum_grid(int g[][3], int rows) so it returns the total of every cell in a grid with rows rows and 3 columns. Do not · 不 write a main. · 完成 int sum_grid(int g[][3], int rows),让它返回一个 rows 行、3 列网格里所有格子的总和。不要写 main。
Click Run to see the output here. · 点击“运行”查看此处输出。
Complete int row_sum(int g[][3], int r) so it returns the total of the three cells in row r. Do not · 不 write a main. · 完成 int row_sum(int g[][3], int r),让它返回第 r 行三个格子的总和。不要写 main。
Click Run to see the output here. · 点击“运行”查看此处输出。
The 2×3 grid g is given. In main, print each row with the three numbers separated by single spaces, one row per line. · 2×3 的网格 g 已经给出。在 main 里面,把每一行的三个数字用单个空格隔开打印,每行一行。
Click Run to see the output here. · 点击“运行”查看此处输出。