尝试在结构中添加数组后的分段错误。

时间:2017-03-28 00:58:22

标签: c arrays structure

我在结构中添加数组中的数据时遇到问题。输入ISBN号后,它会显示错误" Segmentation Fault"它关闭了,我很确定scanf有问题,但我不太清楚为什么。这是我的代码:

#include <stdio.h>
#define MAX_TITTLE_SIZE 20
#define MAX_BOOKS 10
struct Book{
        int _isbn;
        float _price;
        int _year;
        char _title[MAX_TITTLE_SIZE];
        int _qty;
};
int main(void){
        struct Book book[MAX_BOOKS];
        int size=0;
        int opt;
        printf("Welcome to the Book Store\n");
        printf("========================\n");
        while(1){
                menu();
                printf("\n");
                printf("Select: ");
                scanf("%d", &opt);
                if(opt == 1){
                        displayInventory();
                }
                if(opt == 2){
                        addBook();
                }
                if(opt > 3){
                        printf("Invalid input, try again:\n");
                }
                if(opt == 0){
                        printf("Goodbye!\n");
                        return 0;
                }
        }
}
void menu(){
        printf("Please select from the following options:\n");
        printf("1) Display the inventory.\n");
        printf("2) Add a book to the inventory.\n");
        printf("3) Check price.\n");
        printf("0) Exit.\n");
}
void displayInventory(const struct Book book[MAX_BOOKS], const int size){
        if(size >= 1){
                printf("\n");
                printf("Inventory\n");
                printf("====================================================\n");
                printf("ISBN      Title               Year Price  Quantity \n");
                printf("---------+-------------------+----+-------+--------\n");
                printf("%-10.0d%-20s%-5d$%-8.2f%-8d", &book->_isbn, &book->_title, &book->_year, &book->_price, &book->_qty);
        } else {
                 printf("====================================================\n");
                 printf("The inventory is empty!\n");
                 printf("\n");
        }
}
void addBook(struct Book book[MAX_BOOKS], int *size){
        if(*size== MAX_BOOKS){
                printf("The inventory is full\n");
        }
        if(*size < MAX_BOOKS){
                printf("ISBN:");
                scanf("%d", book->_isbn);
                printf("Title:");
                scanf("%c", book->_title);
                printf("Year:");
                scanf("%d", book->_year);
                printf("Price:");
                scanf("%f", book->_price);
                printf("Quantity:");
                scanf("%d", book->_qty);
                printf("The book is successfully added to the inventory.\n");
        }
}

0 个答案:

没有答案