首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C >> C 語言問答

C語言鏈表學生信息系統:結構體定義缺分號導致編譯錯誤

     編輯:C 語言問答

錯誤代碼定位

struct student {
    int num;
    char name[20];
    struct student *next;
}  // ← 此處缺少分號
typedef struct student STU;

編譯器報錯:expected ';' before 'typedef' 或語法錯誤指向 typedef 行。

修正方法

在結構體定義結尾的大括號後加分號:

struct student {
    int num;
    char name[20];
    struct student *next;
};  // ✅ 必須有分號
typedef struct student STU;

完整修正版核心代碼片段

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct student {
    int num;
    char name[20];
    struct student *next;
};
typedef struct student STU;

STU *creat(STU *top);  // 前向聲明

int main() {
    STU *top = NULL;
    top = creat(top);  // 創建鏈表
    // 遍歷輸出
    STU *p = top;
    while (p) {
        printf("%d %s\n", p->num, p->name);
        p = p->next;
    }
    // 釋放內存
    while (top) {
        STU *tmp = top;
        top = top->next;
        free(tmp);
    }
    return 0;
}

STU *creat(STU *top) {
    STU *tail = NULL, *p = NULL;
    int num; char name[20];
    while (1) {
        printf("輸入學號 姓名 (0 結束): ");
        if (scanf("%d %19s", &num, name) != 2) break;
        if (num == 0) break;
        p = (STU *)malloc(sizeof(STU));
        p->num = num;
        strcpy(p->name, name);
        p->next = NULL;
        if (!top) top = tail = p;
        else { tail->next = p; tail = p; }
    }
    return top;
}

鏈表常見錯誤避坑指南

調試技巧

  • 編譯加 -Wall -Wextra -Wpedantic 可捕獲缺分號、格式串等低級錯誤。
  • 用 GDB 斷點在 creat 返回處查看鏈表結構:p top、p top->next->num。
  • Valgrind --leak-check=full 檢測內存洩漏/越界。

「結構體定義以分號結尾」是 C 語言鐵律,養成肌肉記憶可避免大量無謂調試時間。

編譯錯誤截圖修正後運行截圖
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
錯誤類型現象修正
結構體定義缺分號編譯報錯指向後續聲明} 後加 ;
malloc 未判空內存不足時解引用 NULL 崩潰if(!p) { perror("malloc"); exit(1); }
scanf 緩衝區溢出%s 無長度限制%19s 或 fgets
遍歷修改 head 指針丟失鏈表頭,無法釋放/二次使用用臨時指針 p = head 遍歷
釋放後未置 NULL懸空指針,二次 free 崩潰free(p); p = NULL;