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);
}
我对编程很陌生,我不确定我应该怎么做来解决这个问题,我知道它可能与结构体中的指针元素有关。
title
和authors
是未初始化的指针,您需要为它们分配内存(即)让它们指向某个有效的内存位置)如果你想在那里存储任何东西,例如:
book.authors = malloc(100);
book.authors = malloc(100);
表示能够存储99个字符+空结束符' '
的缓冲区。
在这一点上,确保在scanf
中使用大小分隔符,否则有缓冲区溢出的机会,例如:
scanf(" %99[^n]", book.title);
scanf(" %99[^n]", book.authors);
表示100个字符的缓冲区。