图书馆模拟程序出现Segmentation Fault,无法访问公共变量
图书馆模拟程序Add函数段错误问题
我正在编写一个图书馆模拟程序,其中的add函数出现了Segmentation Fault,不清楚故障原因。
函数开头代码:
void add() { Book* newBook = new Book; Book* temp = new Book; temp = head; string tempstring; int id; int n; cout << "Enter the ID of the book you wanna add: "; cin >> id;
下方的if条件用于检查链表是否为空,若为空则添加书籍并退出函数:
if(head == NULL) { newBook->id = id; cout << "Enter the name of the Book: "; cin >> tempstring; newBook->nameOfTheBook = tempstring; cout << "Enter the Name of the Author: "; cin >> tempstring; newBook->author = tempstring; cout << "Enter The number of copys you're going to add: "; cin >> n; newBook->numOfBooks += n; newBook->next = NULL; head = newBook; return; }
我的错误出现在if(temp->id == id)这个条件判断处:
if( while(temp != NULL) { if(temp->id == id) { temp->numOfBooks += 1; if(temp->avaliable == 0) temp->avaliable = 1; return; } temp = temp->next; } newBook->id = id; cout << "Enter the name of the Book: "; cin >> tempstring; newBook->nameOfTheBook = tempstring; cout << "Enter the Name of the Author: "; cin >> tempstring; newBook->author = tempstring; cout << "Enter The number of copys you're going to add: "; cin >> n; newBook->numOfBooks += n;
此时temp的值应为NULL,我尝试将temp替换为newBook:
newBook->prev = temp->prev; newBook->next = NULL; temp->prev->next = newBook; newBook->avaliable = 1; }
内容的提问来源于stack exchange,提问作者kan3
相关产品推荐
相关产品推荐

