我刚刚开始学习C语言,并遇到了一些困难:
下面列出的代码给出了以下错误:
附加到程序:`/ workfolder/cocoa/c_stuff/bookshelf/build/Debug/bookshelf',进程
1674.
无法访问地址0xa0df194的内存无法访问地址0xa0df194的内存
// code start #define MAX_NAME_LENGTH 200 #define MAX_AUTHOR_LENGTH 200 #define MAX_DESCRIPTION_LENGTH 1000 #define MAX_PUBLISHER 200 #define MAX_ISBN 50 //structures< typedef struct { char title[MAX_NAME_LENGTH]; char author[MAX_AUTHOR_LENGTH]; char ISBN[MAX_ISBN]; char description[MAX_DESCRIPTION_LENGTH]; char publisher[MAX_PUBLISHER]; } Book; void getUserInput(Book *s[]) { printf("what is the book's title ?\n"); fgets(s[book_count]->title, MAX_NAME_LENGTH, stdin); printf("what is the author's name?\n"); fgets(s[book_count]->author, MAX_AUTHOR_LENGTH, stdin); printf("what is the ISBN?\n"); fgets(s[book_count]->ISBN, MAX_ISBN, stdin); printf("write a short description\n"); fgets(s[book_count]->description, MAX_DESCRIPTION_LENGTH, stdin); printf("what is the book's publisher\n"); fgets(s[book_count]->publisher, MAX_PUBLISHER, stdin); printf("want to add another book ? Y\\N\n"); book_count++; if(tolower(fgetc(stdin)) == 'y') { return getUserInput(s); } else { return; } } int main (int argc, const char * argv[]) { // insert code here... Book *book_shelf[100]; if((book_shelf[0] = (Book *)malloc(sizeof(Book))) == NULL) { exit(1); } getUserInput(book_shelf); return 0; }
代码编译正确,第一次运行正常(所有问题都被提出,结构接收数据); 但是当用户键入"y"以添加另一本书时,会发生mem错误.
任何错误发生的想法?
提前致谢!
你只为main中的第一本书分配了内存 - 之后它试图写入数组中的下一个插槽,它不指向已分配的内存块,给你一个seg-fault.您将不得不为要阅读的每本书分配内存.
另外,由于C不知道数组有多长,因此必须将该信息传递给函数调用.(而且我没有看到你在哪里定义book_count.)
您可以尝试以下这些方面:
void getUserInput(Book *s[], int *book_count, int max_book_count) { if (book_count == max_book_count) return; // If we've filled all the slots, we can't add anymore without causing trouble. s[book_count] = malloc(sizeof(Book)); .. if(tolower(fgetc(stdin)) == 'y') { (*book_count)++; getUserInput(s, book_count, max_book_count); } return; } int main (int argc, const char * argv[]) { // insert code here... Book *book_shelf[100]; int book_count = 0; getUserInput(book_shelf, &book_count, 100); // Make sure to free all the malloc'd data }
在这种情况下更好的是,只使用循环并跳过整个递归步骤.
int main (int argc, const char * argv[]) { // insert code here... Book *book_shelf[100]; char response = 'y'; int book_count = 0; while (book_count < 100 && response == 'y') { book_shelf = malloc(sizeof(Book)); response = getUserInput(book_shelf[book_count++]); } // make sure to free all the allocated data! } char getUserInput(Book *book) { // write input straight to book printf("what is the book's title ?\n"); fgets(book->title, MAX_NAME_LENGTH, stdin); ... return tolower(fgetc(stdin)); }