1-D arrays: store, index, and traverse · 一维数组:存储、索引与遍历
A row of boxes
- An array is a row of variables of the same type, kept side by side in memory.
int a[5];makes room for fiveints. They are one block, reached by number.- You can fill them when you create them:
int a[] = {10, 20, 30};makes an array of three.
一排盒子
- 数组是一排同样类型的变量,在内存里挨着排放。
int a[5];为五个int腾出空间。它们是一整块,用编号来访问。- 你可以在创建时就填好:
int a[] = {10, 20, 30};创建一个有三个元素的数组。
Indexing from 0
- Each item has an index (a position). The first index is
0, not1. a[0]is the first item,a[1]the second, anda[n - 1]is the last in an array ofnitems.- Reading or writing outside the array (like
a[5]in a 5-item array) is a serious bug.
从 0 开始的下标
- 每个元素都有一个下标(位置)。第一个下标是
0,不是1。 a[0]是第一个元素,a[1]是第二个,在有n个元素的数组里a[n - 1]是最后一个。- 读或写数组之外的位置(比如在 5 个元素的数组里访问
a[5])是严重的错误。
Traversing with a loop
- To visit every item, run an index from
0up ton - 1with aforloop. - Inside the loop, use
a[i]to read or change the item at positioni. - This is how you sum, count, or search an array.
用循环遍历
- 要访问每个元素,用
for循环让下标从0走到n - 1。 - 在循环里面,用
a[i]读或改位置i上的元素。 - 这就是对数组求和、计数或查找的方法。
Arrays don't know their own length
- An array does not carry its own size. A function cannot ask "how long are you?".
- So you always pass the length next to the array:
sum(a, n). - Use
const int a[]in a parameter to promise you will only read the array, not change it.
数组不知道自己的长度
- 数组不带着自己的大小。函数没办法问它“你有多长?”。
- 所以你总是把长度和数组一起传过去:
sum(a, n)。 - 在参数里用
const int a[],表示你保证只读这个数组,不去改它。
#include <stdio.h>
int main(void) {
int a[] = {10, 20, 30, 40};
int n = 4, total = 0;
for (int i = 0; i < n; i++) {
total += a[i];
}
printf("%d\n", total); // 100
return 0;
}
Common mistakes
- C does NOT check array bounds:
a[n]in a size-narray is undefined. - Valid indexes run
0ton - 1.
常见错误
- C 不检查数组越界:大小为
n的数组写a[n]是未定义行为。 - 合法下标是
0到n - 1。
Now you try
- Pass both the array and its length
n, and loop the index from0ton - 1. - For the function tasks, do not write a
main— the checker provides one.
现在轮到你了
- 把数组和它的长度
n一起传进去,让下标从0循环到n - 1。 - 函数任务里,不要自己写
main—— 检查器会提供。
Arrays are indexed · 数组有索引
An array stores values in order; reach one with a[i]. · 数组按顺序存值;用 a[i] 取一个。
The array a and its length n are given. In main, add up all n items and print the total on its own line. · 数组 a 和它的长度 n 已经给出。在 main 里面,把所有 n 个元素加起来,把总和单独打印一行。
Click Run to see the output here. · 点击“运行”查看此处输出。
Complete int sum(const int a[], int n) so it returns the total of the array's n items (0 when n is 0). Do not · 不 write a main. · 完成 int sum(const int a[], int n),让它返回数组中 n 个元素的总和(当 n 为 0 时返回 0)。不要写 main。
Click Run to see the output here. · 点击“运行”查看此处输出。
Complete void double_all(int a[], int n) so it doubles every item of the array, in place (no return value). Do not · 不 write a main. · 完成 void double_all(int a[], int n),让它把数组里每个元素就地翻倍(没有返回值)。不要写 main。
Click Run to see the output here. · 点击“运行”查看此处输出。