為什么我的程序運(yùn)行的時(shí)候顯示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函數(shù)的返回類型是struct weapon指針。
可在函數(shù)中,一開始聲明了p1和p2兩個(gè)指針,然后申請了一段內(nèi)存,讓p1和p2指向它??删o接著就return 0; 了,函數(shù)就返回了!并且返回的是個(gè)NULL指針! ?后面的代碼完全沒用到。
在main中,p得到的就是個(gè)空指針,訪問空指針是不允許的! 所以后面printf在試圖訪問空指針時(shí)就引起了segmentation fault