為什么我的程序運行的時候顯示Segmentation fault (core dumped)
#include <stdio.h>
#include <malloc.h>
struct weapon {
?????? int price;
?????? struct weapon *next;
};
?struct weapon *create(){
?struct weapon *p1,*p2,*head;
?p2=p1=(struct weapon*)malloc(sizeof(struct weapon));
?return 0;
?scanf("%d",&p1->price);
?head=NULL;
?int n=0;
?while(p1->price != 0){
???? n++;
???? if(n==1) head=p1;
???? else p2->next=p1;
?
???? p2=p1;
???? p1=(struct weapon*)malloc(sizeof(struct weapon));
???? scanf("%d",&p1->price);
}
?p2->next = NULL;
?return (head);
}
int main(){
struct weapon *p;
?p=create();
?printf("%d",p->price);
return 0;
}
2015-11-20
create函數的返回類型是struct weapon指針。
可在函數中,一開始聲明了p1和p2兩個指針,然后申請了一段內存,讓p1和p2指向它。可緊接著就return 0; 了,函數就返回了!并且返回的是個NULL指針! ?后面的代碼完全沒用到。
在main中,p得到的就是個空指針,訪問空指針是不允許的! 所以后面printf在試圖訪問空指針時就引起了segmentation fault