📊 Arrays & Multidimensional Arrays数组与多维数组

Master array operations, memory layout, and example problems掌握数组操作、内存布局与示例问题

Array Basics数组基础概念

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]
                
// 数组声明和初始化 int arr1[5]; // 声明5个整数的数组 int arr2[5] = {1, 2, 3, 4, 5}; // 声明并初始化 int arr3[] = {1, 2, 3, 4, 5}; // 自动推断大小 // 访问数组元素 arr1[0] = 10; // 第一个元素 arr1[4] = 50; // 最后一个元素

💡 数组与指针的关系

  • Array name points to the first element数组名是指向第一个元素的指针
  • arr[i] is equivalent to *(arr + i)arr[i]等价于*(arr + i)
  • &arr[i] is equivalent to arr + i&arr[i]等价于arr + i

Two-Dimensional Arrays二维数组

A 2D array is an array of arrays, commonly used to represent matrices or tables. 二维数组是数组的数组,常用于表示矩阵、表格等数据结构。

2D Array Memory Layout (Row-major):二维数组内存布局(行优先):
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]
                
// 二维数组声明和初始化 int matrix[3][4] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} }; // 访问二维数组元素 matrix[0][0] = 100; // 第一行第一列 matrix[2][3] = 200; // 第三行第四列 // 遍历二维数组 for (int i = 0; i < 3; i++) { for (int j = 0; j < 4; j++) { printf("%d ", matrix[i][j]); } printf("\n"); }

Average Temperature Example温度平均值计算

A classic Week 1 exercise: compute daily average temperatures. This is a typical use of a 2D array. Week 1 的经典练习:计算每日平均温度。这是一个典型的二维数组应用。

#define N_DAYS 3 #define N_READINGS 5 void daily_avg_temp(int daily_temperature[N_COLS][N_ROWS]) { // 遍历每一天 for (int day = 0; day < N_DAYS; day++) { int sum = 0; // 计算当天所有温度读数的总和 for (int reading = 0; reading < N_READINGS; reading++) { sum += daily_temperature[day][reading]; } // 计算并打印平均温度 int average = sum / N_READINGS; printf("Average temperature for day %d = %d\n", day, average); } }

🎯 温度数据示例

int main() { // 3天,每天5个温度读数 int temps[N_DAYS][N_READINGS] = { {20, 22, 25, 23, 25}, // 第1天 {26, 28, 30, 27, 29}, // 第2天 {18, 20, 22, 19, 21} // 第3天 }; daily_avg_temp(temps); return 0; }

Output:输出结果:

Average temperature for day 0 = 23 Average temperature for day 1 = 28 Average temperature for day 2 = 20

Arrays as Function Parameters数组作为函数参数

Arrays can be passed to functions, but there are special syntax rules (especially for multi-dimensional arrays). 数组可以作为函数参数传递,但存在一些特殊语法(尤其是多维数组参数)。

// 一维数组作为参数 void print_array(int arr[], int size) { for (int i = 0; i < size; i++) { printf("%d ", arr[i]); } printf("\n"); } // 二维数组作为参数(必须指定列数) void print_matrix(int matrix[][4], int rows) { for (int i = 0; i < rows; i++) { for (int j = 0; j < 4; j++) { printf("%d ", matrix[i][j]); } printf("\n"); } }

⚠️ Bounds Checking数组边界检查

C does not perform bounds checking. Out-of-bounds access results in undefined behavior: C 语言不会自动检查数组边界,越界访问会导致未定义行为:

int arr[5] = {1, 2, 3, 4, 5}; printf("%d\n", arr[10]); // 危险!数组越界 arr[-1] = 100; // 危险!负数索引

Arrays and Pointer Arithmetic数组与指针算术

Understanding how arrays are laid out in memory is crucial for writing efficient C code. 理解数组在内存中的布局对于高效编程很重要。

int arr[5] = {10, 20, 30, 40, 50}; // 数组名是指向第一个元素的指针 int *ptr = arr; // 等价于 &arr[0] // 指针算术 printf("%d\n", *ptr); // 10 printf("%d\n", *(ptr + 1)); // 20 printf("%d\n", *(ptr + 2)); // 30 // 数组索引 vs 指针算术 printf("%d\n", arr[3]); // 40 printf("%d\n", *(arr + 3)); // 40 (等价)

💡 性能考虑

  • Array access is O(1)数组访问是O(1)时间复杂度
  • Contiguous memory improves cache locality连续存储有利于缓存局部性
  • Pointer arithmetic can be more efficient than indexing指针算术比数组索引有时更高效

🎯 Practice & Consolidation练习与巩固

练习1: 数组查找最大值

Write a function to find the maximum value in an array and its index:编写函数找到数组中的最大值及其索引:

void find_max(int arr[], int size, int *max_value, int *max_index) { // 在这里实现查找最大值的逻辑 // 使用指针参数返回结果 }

Answer:答案:

void find_max(int arr[], int size, int *max_value, int *max_index) { *max_value = arr[0]; *max_index = 0; for (int i = 1; i < size; i++) { if (arr[i] > *max_value) { *max_value = arr[i]; *max_index = i; } } }

练习2: 矩阵转置

Implement a matrix transpose function:实现矩阵转置函数:

void transpose_matrix(int matrix[3][3], int result[3][3]) { // 实现矩阵转置 // result[i][j] = matrix[j][i] }

Answer:答案:

void transpose_matrix(int matrix[3][3], int result[3][3]) { for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { result[i][j] = matrix[j][i]; } } }

Summary总结

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的所有核心概念。这些基础将为你后续学习更复杂的数据结构和算法打下坚实基础。