【发布时间】:2021-05-29 15:18:41
【问题描述】:
struct Book {
char *title;
char *authors;
unsigned int year;
unsigned int copies;
};
void book_to_add()
{
struct Book book;
struct Book *ptrbook = (struct Book*) malloc(sizeof(struct Book));
printf("Book you would like to add: \n");
scanf("%[^\n]", book.title);
printf("Author of Book: \n");
scanf("%[^\n]", book.authors);
printf("Year book was published: \n");
scanf("%u", &book.year);
printf("number of copies: \n ");
scanf("%u", &book.copies);
add_book(book);
free(ptrbook);
}
我对编程很陌生,我不确定我应该怎么做才能解决这个问题,我知道这可能与结构中的指针元素有关。
【问题讨论】:
-
在
scanf()中的%之前添加一个空格,以使用可选的前导空格:scanf(" %[...]", ...)
标签: c pointers struct segmentation-fault malloc