程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> malloc-C語言動態鏈表建立問題

malloc-C語言動態鏈表建立問題

編輯:編程綜合問答
C語言動態鏈表建立問題

#include
#include
#define LEN sizeof(struct Student)

int n = 0;//記錄數據的個數

struct Student
{
    int number;
    int score;
    struct Student *next;
};


int main()
{
    struct Student *creat(void);
    void print(struct Student *p);
    struct Student *p;
    p = creat();
    print(p);
    return 0;
}


struct Student *creat(void)
{
    struct Student *p1,*p2;
    struct Student *head = NULL;
    p1 = p2 = (struct Student *)malloc(LEN);
    printf("please enter Students' informations(number & score:)");
    scanf("%d %d",&p1->number,&p1->score);//get
    while(p1->number != 0)
    {
        n += 1;
        if(n==1)head = p1;
        else p2->next = p1;
        p2 = p1;
        printf("please enter Students' informations(number &score):");
        scanf("%d %d",p1->number,p1->score);
        p1 = (struct Student*)malloc(LEN);

    }
   p2->next = NULL;
   return (head);
};


void print(struct Student *p)
{
    printf("their informations as follows:\n");
    while(p->number!=0)
    {
        printf("%d %d",p->number,p->score);
        p = p->next;
    }
}

代碼如上,運行後輸入第二個數據後顯示“該內存不能為written”,用的是CODEBLOCKS。卡在這一天了,求解答,萬分感謝~

最佳回答:


while(p1->number != 0) { n += 1; if(n==1)head = p1; else p2->next = p1; p2 = p1; printf("please enter Students' informations(number &score):"); scanf("%d %d",p1->number,p1->score); p1 = (struct Student*)malloc(LEN); }

檢查這裡的scanf函數

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved