//samplecode1#include#defineLEN41structbook{chartitle[LEN];charauthor[LEN];}intmain(){structbook*b;//有意義的指針printf("Enterthebooktitle:");scanf("%40s",b->title);printf("Enterthebookauthor:");scanf("%40s",b->author);return0;}//samplecode2#include#defineLEN41structbook{chartitle[LEN];charauthor[LEN];}structbook*newBook();intmain(){structbook*b;//有意義的指針b=newBook();return0;}structbook*newBook(){structbook*temp;//NULL指針,為何?printf("Enterthebooktitle:");scanf("%40s",temp->title);printf("Enterthebookauthor:");scanf("%40s",temp->author);returntemp;}為什么上面兩段代碼,第一段可以跑,第二段在跑newBook()的時(shí)候就會(huì)報(bào)Segmentationfault..后來(lái)我在第二段代碼中用structbook*temp=(structbook*)malloc(sizeof(structbook));之后第二段就不會(huì)報(bào)錯(cuò)了。。就有個(gè)疑問(wèn)了。在第一段代碼main中定義的book結(jié)構(gòu)指針。這個(gè)指針是個(gè)有意義的指針。但是到了第二段代碼的newBook方法中定義的話,就會(huì)是NULL指針。。求解。
C語(yǔ)言聲明結(jié)構(gòu)的指針的問(wèn)題。
慕斯王
2019-04-16 20:27:51