亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

大佬們幫我看看這個程序怎么會這樣。運行一下輸入兩個數后。

大佬們幫我看看這個程序怎么會這樣。運行一下輸入兩個數后。

C C++
qq_踩踩踩_0 2018-03-29 21:07:47
#include?<iostream> using?namespace?std; #include?<stdlib.h> struct?list {? int?data; struct?list?*next; }; struct?list?*?creatlist()??//創建一個帶頭結點的單向鏈表,鏈表結點中的數據通過鍵盤輸入,當輸入數據為-1時,表示輸入結束。 { struct?list?*p1,*p2,*head; int?n=1; head=NULL; p1=p2=(?struct?list*)malloc(sizeof(struct?list)); cout<<"number"<<endl; cin>>p1->data; while(p1->data!=(-1)) { if(n==1)head=p1; else?p2->next=p1; p2=p1; free(p1); cin>>p1->data; } p2->next=NULL; return(head); } void?print(list?*L)??//打印鏈表 { ??struct?list?*p; ??p=L; ??do ??{ ??cout<<p->data<<endl; ??p=p->next; ??}while(p!=NULL); } void?Comput(list?*L)??//求其數據域的總和與平均值 { struct?list?*p; int?n,x; n=x=0; p=L; while(p!=NULL) { x+=p->data; p=p->next; n++; } n=x/n; cout<<"aver="<<n<<"sum="<<x<<endl; } void?main()????? { struct?list?*head; head=creatlist(); print(head); Comput(head); }
查看完整描述

1 回答

?
onemoo

TA貢獻883條經驗 獲得超454個贊

先說最明顯的。第 24 行,你把 p1 free 了! 那么 25 行再次訪問 p1 就已經不正確了!

而且,在 19 行的 while 循環中,由于 n 的值沒有變化,所以每次循環都會執行 21 行——也就是每次 head 和 p2 都指向 p1 所指的節點。? 但在第一次循環執行 24 行以后,p1 所指的節點已經不合法了,所以整個 while 就是不斷向一個不合法的內存中寫入數據!? 鏈表根本就沒有建立起來。

其他代碼還沒有看,但?creatlist 中的問題就不小了...


還有,你這個是 C++ 代碼吧?? ?在 C++ 中的沿襲的 C 語言庫函數的頭文件名并不是 C 語言風格的 xxx.h,而是 cxxx!? 比如 stdlib.h 這個 C 語言庫函數頭文件在 C++ 中應該寫 <cstdlib>。? 一個標準的 C++ 環境中就沒有?stdlib.h 這個頭文件!

查看完整回答
反對 回復 2018-03-31
  • 1 回答
  • 0 關注
  • 920 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號