[英]Using a malloc for an int array in typedef struct
我在使用 malloc 作为 C 中 typedef 结构中的数组时遇到了问题。 我不知道如何在 typedef 结构中进行动态分配,编译器不报告错误,但程序打开和关闭返回 -1073741819。 在程序中,我正在阅读餐厅的评论数量,以获得餐厅本身的平均评论。
typedef struct{
int number_of_evaluations;
int *evaluations;
}reviews;
reviews arr_rew[LEN]; //Where LEN=200
void charge_review(review arr_rew[LEN]){
FILE *fp;
fp = fopen("recensioni.txt", "r");
if(fp == NULL) {
puts("================\nFile didn't opened\n================");
}
else
{
for(i=0;!feof(fp);i++)
{
fscanf(fp, "%d", arr_rew[i].number_of_evaluations);
reviews* evaluations=malloc(arr_rew[i].number_of_evaluations*sizeof(int));
for(int j=0;j<arr_rew[i].number_of_evaluations;j++)
{
fscanf(fp, "%d", arr_rew[i].evaluations);
}
fclose(fp);
}
}
}
我做错了什么? - - 对不起,我的英语不好
我做错了什么?
您分配了evaluations
,但编写了arr_rew[i].evaluations
unitialised 并且没有按j
索引。
改变:
reviews* evaluations=malloc(arr_rew[i].number_of_evaluations*sizeof(int));
至
arr_rew[i].evaluations = malloc( arr_rew[i].number_of_evaluations * sizeof(int) ) ;
(或更好):
arr_rew[i].evaluations = malloc( arr_rew[i].number_of_evaluations *
sizeof(*arr_rew[i].evaluations) ) ;
和
fscanf(fp, "%d", arr_rew[i].evaluations) ;
至
fscanf( fp, "%d", arr_rew[i].evaluations[j] ) ;
您还在写入文件时也会关闭文件,并且以这种方式使用feof()
是有缺陷的,因为只有在您尝试读取文件末尾之后才是正确的。 而是检查文件 i/o 操作是否成功,如果失败则退出循环。
int input_check = 1 ;
for( int i = 0; input_check != 0; i++ )
{
input_check = fscanf(fp, "%d", arr_rew[i].number_of_evaluations);
if( input_check != 0 )
{
arr_rew[i].evaluations = malloc( arr_rew[i].number_of_evaluations *
sizeof(*arr_rew[i].evaluations) ) ;
for( int j = 0; input_check != 0; j < arr_rew[i].number_of_evaluations; j++ )
{
input_check = fscanf( fp, "%d", arr_rew[i].evaluations[j] ) ;
}
}
}
fclose( fp ) ;
您需要将malloc()
的结果分配给arr_rew[i].evaluations
。 然后您需要在读取评估值时对该数组进行索引。
并且evaluations
应该是int*
,就像reviews
结构的evaluations
成员一样。
void charge_review(review arr_rew[LEN]){
FILE *fp;
fp = fopen("recensioni.txt", "r");
if(fp == NULL) {
puts("================\nFile didn't opened\n================");
}
else
{
for(i=0;;i++)
{
if (fscanf(fp, "%d", arr_rew[i].number_of_evaluations) != 1) {
break;
}
int* evaluations=malloc(arr_rew[i].number_of_evaluations*sizeof(int));
for(int j=0;j<arr_rew[i].number_of_evaluations;j++)
{
fscanf(fp, "%d", &evaluations[j]);
}
arr_rew[i].evaluations = evaluations;
}
fclose(fp);
}
}
其他问题:
!feof(fp)
作为循环条件。 请参阅为什么“while (?feof (file))”总是错误的? 由于这个原因。 请检查fscanf()
的结果。fclose(fp)
需要在循环之外。感谢大家,代码现在终于可以与memory:D的动态分配一起使用了
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.