我的C线怎么了?(关于结构数组指针)



首先定义一个结构体

struct book_record{
char book_name[52];
char publisher_name[32];
char name[32];
int publishing_year;
int page;

};

和我做了一个这样的绳子。

FILE* book_data = fopen("book.txt", "rt"); 
FILE* book_file = fopen("book2.txt","wt"); 
int input, i, j;
fscanf(book_data, "%d", &input);
struct book_record *m[input];
for(i=0; i<input; i++){
m[i] = (struct book_record *)malloc(sizeof(struct book_record));
}
enter
我觉得这条线没有问题。但是我的老师告诉我这条线有大问题。老师说因为"输入";未初始化,struct record *m[input]有错误。但是我认为我在*m[input]之前用'fscanf'清楚地声明了input。我听不懂老师说的话。帮助我。
int input, i, j;

此时,inputij均无特殊值;它们的内容是不确定

是的,您正在尝试在使用input之前读取它的值:

fscanf(book_data, "%d", &input);
struct book_record *m[input];

但是fscanf操作可能会失败-如果book_data流中的第一个字符不是十进制数字,或者如果流有问题,那么fscanf不会给input分配任何东西,它仍然会有不确定的值(可能是正的,负的,零,非常大,等等)。

fscanf返回成功转换和分配的项数,如果看到文件结束或错误,则返回EOF—在本例中,您希望读取1项,因此fscanf应该在成功时返回1。在使用input:

之前,您应该检查返回值
if ( fscanf( book_data, "%d", &input ) != 1 )
{
fputs( "Error reading input from book_data, exitingn", stderr );
exit( 0 );
}
struct book_record *m[input];

如果由于任何原因fscanf操作失败,我们将在尝试使用input之前退出程序。

在尝试使用这些流之前,您还应该确保fopen调用成功:

FILE* book_data = fopen("book.txt", "rt"); 
if ( !book_data )
{
fputs( "Could not open book.txt, exiting...n", stderr );
exit( 0 );
}
FILE* book_file = fopen("book2.txt","wt"); 
if ( !book_file )
{
fputs( "Could not open book2.txt, exiting...n", stderr );
fclose( book_data ); 
exit( 0 );
}

最新更新