Master array operations, memory layout, and example problems掌握数组操作、内存布局与示例问题
An array in C stores multiple elements of the same type in contiguous memory. This contiguity enables fast indexing and predictable memory accesses. 数组是 C 语言中最基本的数据结构,用于存储相同类型的多个元素,并在内存中连续存储,有利于快速索引与可预测的内存访问。
int arr[5] = {10, 20, 30, 40, 50};
内存地址:
+------+------+------+------+------+
| 10 | 20 | 30 | 40 | 50 |
+------+------+------+------+------+
0x100 0x104 0x108 0x10C 0x110
arr[0] arr[1] arr[2] arr[3] arr[4]
A 2D array is an array of arrays, commonly used to represent matrices or tables. 二维数组是数组的数组,常用于表示矩阵、表格等数据结构。
int matrix[3][4] = {
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12}
};
内存中连续存储:
+------+------+------+------+------+------+------+------+------+------+
| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 |
+------+------+------+------+------+------+------+------+------+------+
matrix[0][0]...matrix[0][3] matrix[1][0]...matrix[1][3] matrix[2][0]...matrix[2][3]
A classic Week 1 exercise: compute daily average temperatures. This is a typical use of a 2D array. Week 1 的经典练习:计算每日平均温度。这是一个典型的二维数组应用。
Output:输出结果:
Arrays can be passed to functions, but there are special syntax rules (especially for multi-dimensional arrays). 数组可以作为函数参数传递,但存在一些特殊语法(尤其是多维数组参数)。
C does not perform bounds checking. Out-of-bounds access results in undefined behavior: C 语言不会自动检查数组边界,越界访问会导致未定义行为:
Understanding how arrays are laid out in memory is crucial for writing efficient C code. 理解数组在内存中的布局对于高效编程很重要。
Write a function to find the maximum value in an array and its index:编写函数找到数组中的最大值及其索引:
Answer:答案:
Implement a matrix transpose function:实现矩阵转置函数:
Answer:答案:
Arrays are a fundamental building block in C. In this module, you learned: 数组是C语言编程的基础,本周我们学习了:
After learning arrays, you’ve mastered all core Week 1 concepts. These foundations prepare you for more advanced data structures and algorithms.完成了数组学习后,你已经掌握了Week 1的所有核心概念。这些基础将为你后续学习更复杂的数据结构和算法打下坚实基础。