尝试将用户输入分配给结构中的元素,但不断出现分段错误 11
Trying to assign user input to elements in a struct but keep getting segmentation-fault 11
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 个字符 + 空终止符的缓冲区 '[=14=]'
。
请注意,请确保在 scanf
中使用大小分隔符,否则可能会出现缓冲区溢出,e.g:
scanf(" %99[^\n]", book.title);
scanf(" %99[^\n]", book.authors);
对于 100 个字符的缓冲区。
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 个字符 + 空终止符的缓冲区 '[=14=]'
。
请注意,请确保在 scanf
中使用大小分隔符,否则可能会出现缓冲区溢出,e.g:
scanf(" %99[^\n]", book.title);
scanf(" %99[^\n]", book.authors);
对于 100 个字符的缓冲区。