请帮助我调试此代码。它没有显示正确的数据。下面的程序应该从用户那里获取书籍的详细信息,动态地为它们分配内存并显示它们。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "problem5.h"
int main()
{
struct books *b;
b = (struct books*)malloc(sizeof(struct books));
int command, flag = 0;
int n=0, i;
while(flag == 0)
{
printf ("1. Add Bookn");
printf ("2. View Booksn");
printf ("3. Quitn");
scanf("%d", &command);
if (command == 1)
{
printf ("Enter Namen");
//scanf("%d", &(b+i)->name);
scanf(" ");
gets((b+i)->name);
printf ("Enter Authorn");
//scanf("%d", &(b+i)->author);
scanf(" ");
gets((b+i)->author);
printf ("Enter Year Publishedn");
scanf("%d", &(b+i)->year_published);
n=n+1;
i=n;
} else if (command == 2)
{
for(i=0; i<n; i++)
{
printf ("%d - %d by %dn", (b+i)->year_published, (b+i)->name, (b+i)->author);
}
} else if (command == 3)
{
flag = 1;
} else
{
printf ("Invalid choice!n");
}
}
}
以下是problem5.h头文件,该文件具有结构书。最初我没有在数组中声明变量,因为我不想使用太多内存。但由于许多错误,我不得不这样做。
#define PROBLEM3_H_INCLUDED
typedef struct books{
char *name[30];
char *author[30];
int year_published;
};
#endif // PROBLEM3_H_INCLUDED
当我打印时,我得到的是随机数字,而不是用户输入的数据。
代码的总体设计是错误的。
这基本上就是你想要的。
我做了以下更改:
- 使用有意义的变量名
- 更改了
struct book
,使结构可以包含一本书。还将其从struct books
重命名为struct book
,因为该结构只包含一本书 - 正确分配内存
- 使用
books[numberofbooks].x
而不是可读性较差的*(books + numberofbooks)->x
评论中的更多解释。
#include <stdio.h>
#include <stdlib.h>
struct book {
char name[30];
char author[30];
int year_published;
};
int main()
{
struct book* books = NULL; // no books at all initially so we
// initialize to NULL
// so we can simply use realloc
int numberofbooks = 0;
int programend = 0;
while (programend == 0)
{
printf("1. Add Bookn");
printf("2. View Booksn");
printf("3. Quitn");
int command;
scanf("%d", &command);
if (command == 1)
{
getchar(); // consume Enter key (due su scanf)
// allocate memory for one more book
books = realloc(books, sizeof(struct book) * (numberofbooks + 1));
printf("Enter Namen");
gets(books[numberofbooks].name);
printf("Enter Authorn");
gets(books[numberofbooks].author);
printf("Enter Year Publishedn");
scanf("%d", &books[numberofbooks].year_published);
numberofbooks++; // increment number of books
}
else if (command == 2)
{
for (int i = 0; i < numberofbooks; i++)
{
printf("%d - %s by %sn", books[i].year_published, books[i].name, books[i].author);
}
}
else if (command == 3)
{
programend = 1;
}
else
{
printf("Invalid choice!n");
}
}
}
但仍有改进的空间:
realloc
的错误检查- 交互式I/O的错误检查
- 不使用已弃用且危险的
gets
- 当然还有其他一些事情
b = (struct books*)malloc(sizeof(struct books));
这里,您只为struct books
的一个实例分配内存,但您正在访问struct books
的多个实例。
printf ("%d - %d by %dn", (b+i)->year_published, (b+i)->name, (b+i)->author);
对于i>=1
,没有定义(b+i)
,因为您没有为其分配内存。您只为(b+0)
分配了内存。
int n=0, i;
gets((b+i)->name);
此处,i
尚未初始化。