輸入 6 位學生、5 門課程的成績,計算每位學生平均分與每門課程平均分。使用二維陣列與指標傳遞實作。
#include
#define STUDENTS 6
#define COURSES 5
// 函式宣告:參數為「指向含 COURSES 個 int 的陣列指標」
void input_scores(int (*scores)[COURSES]);
void avg_per_student(int (*scores)[COURSES]);
void avg_per_course(int (*scores)[COURSES]);
int main(void)
{
int scores[STUDENTS][COURSES]; // 6 列 (學生) x 5 行 (科目)
input_scores(scores);
avg_per_student(scores);
avg_per_course(scores);
return 0;
}
// 輸入成績
void input_scores(int (*scores)[COURSES])
{
for (int i = 0; i < STUDENTS; i++)
{
printf("輸入第 %d 位學生 %d 科成績: ", i + 1, COURSES);
for (int j = 0; j < COURSES; j++)
{
scanf("%d", &scores[i][j]); // 等價於 *(scores[i] + j)
}
}
}
// 計算並印出每位學生平均
void avg_per_student(int (*scores)[COURSES])
{
printf("\n=== 各學生平均分 ===\n");
for (int i = 0; i < STUDENTS; i++)
{
int sum = 0;
for (int j = 0; j < COURSES; j++)
sum += scores[i][j];
printf("學生 %2d: 平均 = %.2f\n", i + 1, (float)sum / COURSES);
}
}
// 計算並印出每門課程平均
void avg_per_course(int (*scores)[COURSES])
{
printf("\n=== 各科目平均分 ===\n");
for (int j = 0; j < COURSES; j++)
{
int sum = 0;
for (int i = 0; i < STUDENTS; i++)
sum += scores[i][j];
printf("科目 %2d: 平均 = %.2f\n", j + 1, (float)sum / STUDENTS);
}
}
int (*scores)[COURSES]:`scores` 是**指向「包含 COURSES 個 int 的陣列」的指標**。scores (int [6][5]) 連續佈局: Row 0: [0,0] [0,1] [0,2] [0,3] [0,4] Row 1: [1,0] [1,1] [1,2] [1,3] [1,4] ... Row 5: [5,0] [5,1] [5,2] [5,3] [5,4] scores + i 偏移 i * COURSES * sizeof(int) bytes
| 錯誤寫法 | 問題 | 正確寫法 |
|---|---|---|
| `void f(int **scores)` | 指標的指標,不匹配二維陣列退化型別 | `void f(int (*scores)[COLS])` |
| `void f(int scores[][])` | 缺少第二維大小,編譯錯誤 | `void f(int scores[][COLS])` 或指標寫法 |
| `scanf("%d", scores[i] + j)` | 缺少 & 取址 | `scanf("%d", &scores[i][j])` |
int **scores = malloc(STUDENTS * sizeof(int*));
for (int i = 0; i < STUDENTS; i++)
scores[i] = malloc(COURSES * sizeof(int));
// 使用 scores[i][j] 同樣可行,但記憶體不連續,釋放需逐列 free
C 語言二維陣列作為函式參數時,**必須宣告第二維大小**,使用「指向陣列的指標」(`int (*arr)[COLS]`) 為最標準、可移植的寫法。本範例展示輸入、列平均、行平均三大基本統計操作,奠定陣列指標操作基礎。