第 5 课:strings、2D arrays 与 structs
非 UNSW 官方材料。本文基于官方 Week 04/05 的 strings、2D arrays、array of structs 与 command-line 相关 lecture slides 做中文转述;练习模板为本站原创。[S013][S014][S015]
今天只做:string、2D array、struct array 各读一个最小模板。 下一步:主控台 · 上一课 · 下一课:命令行参数、多文件与指针入门 别乱跳:2D array 永远先写 row,再写 col。
本课目标
今天只抓 3 件事:string 当 char array 读,2D array 先 row 再 col,struct array 先取出一个元素再看字段。[S013][S014][S015]
| 焚诀 | 先做什么 |
|---|---|
| string | 一格一格看字符 |
| 2D array | 外层 row,内层 col |
| array of structs | students[i].field |
最小模板
2D array 题不要先想图形,先写两层循环;这个写法对应官方 2D arrays 主题,但代码是原创练习模板。[S014][S015]
int count_target(int grid[][NUM_COLS], int rows, int target) {
int count = 0;
for (int row = 0; row < rows; row++) {
for (int col = 0; col < NUM_COLS; col++) {
if (grid[row][col] == target) {
count++;
}
}
}
return count;
}
struct array 读法
Lecture 7 提到 array of structs 的视觉理解;保命读法是:先定位 i,再读字段,不要同时脑补太多层。[S013]
CodeBlock Loading...
5 分钟练习
- 写一个循环数出 string 里有几个
'a'。 - 写一个 2D array 循环,把每一行的总和打印出来。
- 写一个 struct array 循环,找最高
mark。
本课过关标准
- 我知道 string 本质上可以按
word[i]逐字符处理。 - 我能写
grid[row][col]。 - 我知道每一行的
sum要在 row 循环里重置。 - 我能读懂
students[i].mark。
引用
- [S013] Lecture 7 PDF: https://cgi.cse.unsw.edu.au/~cs1511/26T1/slides/week_4/COMP1511_26T1_Lecture07.pdf
- [S014] Lecture 8 PDF: https://cgi.cse.unsw.edu.au/~cs1511/26T1/slides/week_4/COMP1511_26T1_Lecture08.pdf
- [S015] Lecture 9 PDF: https://cgi.cse.unsw.edu.au/~cs1511/26T1/slides/week_5/COMP1511_26T1_Lecture09.pdf