萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

C 語言二維陣列指標傳遞與學生成績統計完整範例

題目需求

輸入 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 (*)[COURSES]`)。
  • 函式內 `scores[i]` 即第 i 列的首元素位址,`scores[i][j]` 或 `*(*(scores+i)+j)` 存取元素。
  • **必須在參數中指定第二維大小 `COURSES`**,編譯器才能計算列跨度 (row stride) 正確定址。

記憶體佈局圖解

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]`) 為最標準、可移植的寫法。本範例展示輸入、列平均、行平均三大基本統計操作,奠定陣列指標操作基礎。

copyright © 萬盛學電腦網 all rights reserved