[英]How to add data to structures with a dynamic array in C?
this is my first post on Stack-overflow, I hope I'm not posting a duplicate question but a I couldn't find any reference on this matter.这是我在 Stack-overflow 上的第一篇文章,我希望我没有发布重复的问题,但我找不到关于这个问题的任何参考资料。 I have a "library management system" project in C, where I have to add books to the "library" by using an array of pointers pointing to the structures (books).
我在 C 中有一个“图书馆管理系统”项目,我必须使用指向结构(书籍)的指针数组将书籍添加到“图书馆”。 the problem is I tried a lot of things and nothing worked so far and last thing I tried gave me a lot of errors.
问题是我尝试了很多东西,但到目前为止没有任何效果,我尝试的最后一件事给了我很多错误。
So basically I have this system in which there is a main menu, the user chooses an input to: a.所以基本上我有这个系统,其中有一个主菜单,用户选择一个输入: Add/return book b.
添加/归还书籍 b. Take a book c.
拿一本书 c。 Print books by times borrowed from the library d.
按从图书馆借阅的次数打印书籍 d. Quit
退出
the rest of the options are easy to deal with if I understand how to add data into a structure.如果我了解如何将数据添加到结构中,则选项的 rest 很容易处理。 my code so far looks like this:
到目前为止,我的代码如下所示:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#define BOOK_NUM 4
#define NAME_LENGTH 200
#define AVAILABLE 10
#define NOT_AVAILABLE 20
int menu_on=1;
//~~~~~~~~~~~~~~~~~~~~~~
typedef struct book {
char name[NAME_LENGTH];
char author[NAME_LENGTH];
int available;
int times_borrowed;
} book;
book* Books[BOOK_NUM];
void AddBook()
{
char name[NAME_LENGTH];
printf("Please enter book name:");
scanf("%s", name);
for (int i=0;i<BOOK_NUM;i++)
{
if(name!=Books[i]->name)
{
Books[i]= malloc(sizeof(book));
if((Books[i]=NULL))
{
free(Books);
free(Books[i]);
exit(1);
}
strcpy(Books[i]->name, name); // here is the problem**
printf("Please enter author name:");
scanf("%s", Books[i]->author);
Books[i]->available=AVAILABLE;
Books[i]->times_borrowed=0;
printf("The book %s was successfully added!\n", name);
break;
}
else if ((name == Books[i]->name) && (Books[i]->available==AVAILABLE))
{
printf("This book is already in the library :)");
}
else if ((name == Books[i]->name) && (Books[i]->available==NOT_AVAILABLE))
{
ReturnBook(name); //this function is for later.
}
}
}
what I'm trying to do is just add one book at a time, allocate memory for it, and then the rest of the details.我要做的只是一次添加一本书,为其分配memory,然后是细节的rest。 at most the "library" includes 4 books.
“图书馆”最多包括4本书。
The rest of the stuff can be done easily if I just know how to add these books and use the dynamic array with its content.如果我只知道如何添加这些书籍并使用动态数组及其内容,那么这些东西的 rest 可以轻松完成。
The error I receive is: EXC_BAD_ACCESS (code=1, address=0x0)我收到的错误是:EXC_BAD_ACCESS (code=1, address=0x0)
if((Books[i]==NULL))
{
free(Books);
free(Books[i]);
exit(1);
}
Here, you should use ==
not =
.在这里,您应该使用
==
而不是=
。 Using =
will make Books[i] = NULL
.使用
=
将使Books[i] = NULL
。
And use strcmp
for string comparison.并使用
strcmp
进行字符串比较。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.