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

C 語言鏈表創建掃描格式錯誤:scanf 格式字符串寫反導致死循環

     編輯:程式設計綜合問答

錯誤代碼

scanf("d% d%", &(p1->coefficient), &(p1->exponent));

問題

scanf 格式字符串應為 "%d %d",寫成 "d% d%" 導致無法匹配輸入,緩衝區數據不被消費,循環條件 p1->coefficient != -1 永遠滿足 (未讀取到新值),進入死循環/死機。

修正

scanf("%d %d", &(p1->coefficient), &(p1->exponent));

其他隱患

  • #include 缺少頭文件名 (應為 stdio.h、stdlib.h/malloc.h)。
  • malloc 返回值未檢查。
  • 輸出函數 printf("d% d%") 同樣格式錯誤。
  • 鏈表遍歷打印邏輯有誤:while(head != null) 應為 while(p != null),否則無限循環。

完善後的創建與打印

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

typedef struct Faction {
    int coefficient;
    int exponent;
    struct Faction *next;
} Faction;

Faction* creat() {
    Faction *head = NULL, *tail = NULL, *p;
    int coef, exp;
    while (scanf("%d %d", &coef, &exp) == 2) {
        if (coef == -1 && exp == -1) break;
        p = (Faction*)malloc(sizeof(Faction));
        if (!p) { perror("malloc"); exit(1); }
        p->coefficient = coef;
        p->exponent = exp;
        p->next = NULL;
        if (!head) head = p;
        else tail->next = p;
        tail = p;
    }
    return head;
}

void Print(Faction *head) {
    Faction *p = head;
    while (p) {
        printf("%d %d\n", p->coefficient, p->exponent);
        p = p->next;
    }
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved