Two-dimensional arrays
C Programming Lesson 11 2:26 English narration · English + 中文 subtitles burned in
Chapters
Transcript
A seating plan, a chessboard, a month of temperatures for six cities — these are grids, and one index is not enough for them.
座位表、棋盘、六个城市一个月的气温——这些都是网格, 一个下标对它们来说不够用。
So C lets you write two.
所以 C 允许你写两个。
This declaration makes two rows of three columns, six numbers in all, and each one is reached with two indexes.
这条声明造出两行三列,一共六个数, 每一个都用两个下标来取到。
The order matters and it never changes: row first, then column.
顺序很重要而且从不改变:先行,后列。
So this reads as row one, column two, and it holds six.
所以这句读作“第 1 行、第 2 列”,它装的是 6。
To touch every cell you need a loop inside a loop.
要碰到每一个格子,你需要一个循环套在另一个循环里。
The outer one picks a row.
外层循环选定一行。
The inner one walks along it, column by column, and only when it finishes does the outer loop move down.
内层循环沿着这一行一列一列地走, 只有等它走完,外层循环才往下移一行。
Watch the running total: the body runs six times in total, once per cell, which is rows times columns.
看那个累计的总和:循环体一共执行了六次,每个格子一次, 也就是行数乘以列数。
That pattern — outer for rows, inner for columns — is the shape of every grid job in this lesson.
外层管行、内层管列——这一课里所有网格任务都是这个形状。
The grid is how you think about it.
网格是你脑子里的样子。
Memory is not shaped like that.
内存不是这个形状。
All six numbers sit in one straight run, laid end to end: the whole of row zero first, then the whole of row one.
六个数排在一条直线上,首尾相接: 先是整个第 0 行,然后是整个第 1 行。
This is called row-major order, and it explains something that otherwise looks arbitrary.
这叫按行存储,它解释了一件本来看着很随意的事。
To find a cell, the compiler has to know how wide a row is — without that number it cannot work out where row one begins.
要找到某个格子,编译器必须知道一行有多宽—— 没有这个数字,它算不出第 1 行是从哪里开始的。
Which brings us to the lesson's first task: add up the whole grid.
这就带出课程里的第一道题:把整个网格加起来。
The body is the nested loop you just saw.
函数体就是你刚看到的那个嵌套循环。
The part worth memorising is the parameter.
值得背下来的是参数写法。
You may leave the rows blank, because the count comes in separately — but the column count has to be there.
行数可以留空,因为它另外作为参数传进来—— 但列数必须写上。
Take it out and the code will not compile, and now you know exactly why: without the width, row one has no address.
把它去掉,代码就编译不过,而现在你完全知道原因: 没有宽度,第 1 行就没有地址。
Four things to take with you.
带走四点。
One: this declaration is two rows of three columns, and the row index always comes first.
第一:这条声明是两行三列,行下标永远写在前面。
Two: an outer loop for rows, an inner one for columns.
第二:外层循环管行,内层循环管列。
Three: memory holds row zero, then row one, in one line.
第三:内存里先放第 0 行,再放第 1 行,排成一条线。
Four: a parameter may drop the rows, never the columns.
第四:参数里可以省掉行数,绝不能省掉列数。
Now do the three tasks — the second one sums a single row, which is the inner loop on its own.
现在去做那三道题——第二题只求某一行的和, 也就是把内层循环单独拿出来用。