【发布时间】:2016-04-07 05:49:13
【问题描述】:
我要实现以上功能:
struct _book
{
int id;
char name[20];
char Author[20];
int quantity;
float Price;
int rack_no;
};
typedef struct _book book;
typedef struct _node
{
book* data;
struct _node* next;
} Node;
Node* book_list=NULL;
void createPassword(void);
int logIn(void);
void sellBook(void);
void addBook(void);
void changePassword(void);
void searchBook(void);
void printZeroQuantity(void);
void printBooks(void);
void logOut(void);
void updateQuantity(void);
void entry(void);
void deleteBook(void);
void updateQuantity(void);
嘿,我是一个新的“程序员”,不到两个月,我有一个关于 C 中的结构和链表的问题。
我想构建一个应用程序来管理库数据库。
另外,我想接收作为参数获取的实现函数void并返回void,例如像这个函数:addBook(void),这意味着所有结构在整个程序中都是全局的。
我的问题是我如何从函数中读取链表的头部,而不是将指针发送到 link_structures 的顶部,例如:book make_book(book *booklist,int count)。
您认为构建将创建的半函数是否可取?
Node* new_node(int data)还是没必要?
book *Addbook(book *book_list,int *counter)
{
book Newbook;
int size, num, size1, size2, flag, check, i, size3;
char *tempfirst, *templast, *tempphone;
int *temprackno, *tempid;
double *tempprice;
(*counter)++;
book_list = (book*)realloc(book_list, (sizeof(book)*(*counter)));
book_list[*counter-1] = Getbook(book_list, ((*counter-1)));
printf("\nA book was added seccesfully");
return(book_list);
}
book Getbook(book *book_list, int count)
{
book NewBook;
int size, num, size1, size2, flag, check, i, size3, counte;
char *tempfirst, *Author, *tempphone;
int *temprackno = 0, *tempid = 0;
double *tempprice;
tempfirst = (char*)malloc(M*(sizeof(char)));
Author = (char*)malloc(M*(sizeof(char)));
tempphone = (char*)malloc(M*(sizeof(char)));
while((tempfirst==NULL) ||(Author==NULL) || (!tempid) || (!tempprice) )
{
tempfirst = (char*)malloc(M*(sizeof(char)));
Author = (char*)malloc(M*(sizeof(char)));
tempid = (int*)malloc(M*(sizeof(int)));
tempprice = (double*)malloc(M*(sizeof(double)));
}
最后一个问题:这条线有什么问题?程序在运行时挂掉,并且没有向新节点输入任何值。
scanf("%d", &(new_node->data->id));
{
Node* new_node = (Node*) malloc(sizeof(Node));
printf("\nPlease enter the book id:");
scanf("%d", &(new_node->data->id));
printf("\nPlease enter the book name:");
scanf("%s", &(new_node->data->Author));
printf("\nPlease enter the book quantity:");
scanf("%d", &(new_node->data->quantity));
printf("\nPlease enter the book rack:");
scanf("%d", &(new_node->data->rackno));
}
【问题讨论】:
-
有点(和无关)与你的结构命名无关,结构名称存在于它们自己的命名空间中,所以你可以拥有一个与类型别名同名的结构。例如。你可以有
typedef struct book { ... } book;。 -
@JoachimPileborg,使用与结构相同的名称会导致代码读者混淆。强烈建议使用唯一名称
-
关于 C 中对
realloc()1) 的调用,不要从realloc()、calloc()、malloc()转换返回值,因为返回值是void*类型,因此可以赋值到任何指针。强制转换只会使代码混乱,使其更难以理解、调试和维护。 2) 调用realloc()时,始终将返回值分配给临时变量,然后在分配给目标变量之前检查(!=NULL)该临时变量。因为如果realloc()失败了,它可以这样做,那么指向原始内存分配的指针就会丢失,导致内存泄漏。 -
在调用
scanf()和函数族时,始终检查返回值(不是参数值)以确保操作成功。scanf()返回成功输入/转换的次数。如果返回值与格式说明符的数量不匹配,则发生错误。 -
关于这一行:
scanf("%s", &(new_node->data->Author));在 '%s' 格式说明符上没有最大字符修饰符,用户可能会溢出输入缓冲区,这是未定义的行为,并可能导致段错误事件。确保最大字符修饰符比输入缓冲区的实际长度小 1,因为“%s”格式说明符总是将 NUL 字符附加到输入。
标签: c database pointers linked-list structure