Skip to content

Arrays in C

C Programming Lesson 7 2:31 English narration · English + 中文 subtitles burned in

space play · ←/→ 5s · j/l 10s · f fullscreen · ,/. speed

Chapters

Transcript
An array is several boxes of the same type under one name, sitting side by side in memory. 数组是同一种类型的若干个盒子,放在一个名字下面,在内存里紧挨着排列。
You declare it with a size, and you reach an item with square brackets and a position. 声明时要给出大小,取其中一项用方括号加位置。
As everywhere else, the first is index zero. 和别处一样,第一项是索引 0。
So with four items the last is index three, not four — and that off-by-one is about to matter more here than it did in any other language. 所以四项时,最后一项是索引 3,不是 4—— 而这个差一,在这里会比在任何别的语言里都更要紧。
Here is the thing that surprises everyone coming from another language. A C array does not know how long it is. 这里是从别的语言过来的人都会意外的地方:C 的数组不知道自己有多长。
There is no length property to ask, and nothing marks the end — past the last item is simply whatever happens to be in memory next. 没有 length 属性可以问,也没有任何东西标记结尾—— 最后一项之后就是内存里恰好躺着的东西。
So the length is passed beside it, as a second parameter, in every signature you will write. 所以长度要作为第二个参数跟着它一起传,你写的每一个函数签名都是如此。
That is why the tasks all take both a and n. 这就是为什么这些题目里都同时有 a 和 n。
Two lessons ago you saw that an int was copied into a function, so changing it inside changed nothing outside. 两课之前你看到,int 是被复制进函数的,所以在里面改动,外面毫无变化。
An array is different: the function receives the same array, not a copy, so double_all really does change the caller's data. 数组不一样:函数拿到的就是同一个数组,不是副本, 所以 double_all 真的会改动调用者的数据。
That is useful — it is how a function edits your data — and it is dangerous when you did not mean it. 这很有用——函数就是这样修改你的数据的——但在你没打算这么做时它很危险。
So when a function only reads, write const in front, and the compiler will stop you writing to it by accident. 所以当一个函数只读取时,就在前面写上 const,编译器会阻止你不小心写入。
Now the lesson's second task. 现在做课程里的第二道题。
It is the accumulate pattern from lesson four, with one difference: the loop is indexed, because you need a rather than the value itself. 它就是第 4 课的累加模式,只有一个区别: 循环带索引,因为你需要的是 a ,而不是值本身。
Four, twelve, twenty-seven, forty-three. 4、12、27、43。
And look hard at the test — i less than n, never less-than-or-equal. 再仔细看那个判断——i 小于 n,绝不能写小于等于。
Get that wrong and C reads one past the end, prints whatever was there, and tells you nothing at all. 写错了,C 会读到末尾之后的一个位置,把那里的东西打印出来, 而且什么提示都不给你。
Four things to take with you. 带走四点。
One: the first item is index zero and the last is n minus one. 第一:第一项是索引 0,最后一项是 n 减 1。
Two: an array does not know n, so pass it alongside. 第二:数组不知道 n,所以要把它一起传进去。
Three: an array is not copied into a call, so a function can change your data. 第三:数组不会被复制进调用,所以函数能改动你的数据。
Four: const int a says this function only reads, and the compiler will hold you to it. 第四:const int a 表示这个函数只读取,编译器会替你把关。
Now do the three tasks; the last one doubles every item in place. 现在去做那三道题;最后一题要就地把每一项翻倍。

Log in or create account

IGCSE, A-Level & AP