我在一个学校项目中工作,我必须制作一个程序,让用户输入有关新书的信息,删除书或显示所有已注册的书。
[意外的行为是当我选择显示所有书籍时:第二本书的标题始终打印一些奇怪的随机字符或大约15空行,而其余部分保持正常。
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
typedef struct {
int Pages,RlsYear,AtrNbr; //"Pages" stands for "the number of pages", "RlsYear" stands for "Release Year"
char Title[128],Genre[128],Authors[256];
}book;
int main()
{
int i,nb;
char ch1,Tmp[128],cln;
book* b = malloc(1 * sizeof(book));
nb=0;
puts("\n Enter your choice : ");
ch1=getch();
while (ch1 != EOF && ch1 != 'q')
{
switch(ch1) {
case 'n': // N to enter a new book
case 'N':
{
printf("\n enter the book's Title : ");
gets(b[nb].Title);
printf(" enter the book's Genre : ");
gets(b[nb].Genre);
printf(" how many pages does the book have ? ");
scanf("%d",&b[nb].Pages);
gets(cln); //i added those "gets(cln)" to avoid problems from "scanf" so you can just ignore them
printf(" when was the book released (year)? ");
scanf("%d",&b[nb].RlsYear);
gets(cln);
printf(" how many authors does this book have ? ");
scanf("%d",&b[nb].AtrNbr);
gets(cln);
strcpy(b[nb].Authors,"");
for(i=0;i<b[nb].AtrNbr;i++)
{
printf("\t\t enter the %d author : ",i+1);
gets(Tmp);
strcat(b[nb].Authors,Tmp);
strcat(b[nb].Authors," | ");
}
nb=nb+1;
book* B = realloc(b, nb+1 * sizeof(book));
b = B;
}
break;
case 'i': // I to display registered books
case 'I':
{
for(i=0;i<nb;i++)
printf("\n %s",b[i].Title);
}
break;
default:
printf("unknown choice !");
break;
}
puts("\n Enter your choice : ");
ch1=getch();
}
return 0;
}
当我将b.Title
大小从128更改为60时,我解决了这个问题。当b.Title
大小通过80时,显然出现了问题。有人可以解释一下吗?我现在更困惑