我需要一个从文件读取成绩(整数)的函数,并返回一个动态分配的数组,用于存储它们。
这就是我的尝试:
int *readGrades() {
int *grades;
int x;
scanf("%d", &x);
grades = malloc(x * sizeof(int));
return 0;
}
但是,当我运行代码时,我什么也得不到。成绩存储在名为1.in
的文件中:
29
6 3 8 6 7 4 8 9 2 10 4 9 5 7 4 8 6 7 2 10 4 1 8 3 6 3 6 9 4
我使用:./a.out < 1.in
谁能告诉我我做错了什么?
答案 0 :(得分:3)
问题: 以下代码:
int *readGrades() {
int *grades;
int x;
scanf("%d", &x);
grades = malloc(x * sizeof(int));
return 0;
}
从标准输入中读取1 int
,然后它分配一个int
s和return
s 0
的数组,当使用这个时,它会对调用者的指针进行零初始化:
int* grades = readGrades();
解决方案: 除了阅读成绩计数外,该功能还应阅读成绩。应该在读取之前初始化数组,并且应该在循环中完成等级的实际读取,这将初始化数组的元素。最后,应返回指向第一个元素的指针:
int *readGrades(int count) {
int *grades = malloc(count * sizeof(int));
for (i = 0; i < count; ++i) {
scanf("%d", &grades[i]);
}
return grades; // <-- equivalent to return &grades[0];
}
...
int count;
scanf("%d", &count); // <-- so that caller knows the count of grades
int *grades = readGrades(count);
答案 1 :(得分:0)
希望您正在寻找以下计划。这会读取你的grade.txt,创建内存并最终释放。我已经测试了以下程序,它运行正常。
#include "stdio.h"
int main(int argc, char *argv[])
{
FILE *fp;
int temp;
int *grades = NULL;
int count = 1;
int index;
fp = fopen("grades.txt","rb+");
while( fscanf(fp,"%d",&temp) != EOF )
{
if( grades == NULL )
{
grades = malloc(sizeof(temp));
*grades = temp;
printf("The grade is %d\r\n",temp);
}
else
{
printf("The grade is realloc %d\r\n",temp);
count++;
grades = realloc(grades,sizeof(grades)*count);
index = count -1;
*(grades+index) = temp;
//printf("the index is %d\r\n",index);
}
}
/** lets print the data now **/
temp = 0;
while( index >= 0 )
{
printf("the read value is %d\r\n",*(grades+temp));
index--;
temp ++;
}
fclose(fp);
free(grades);
grades = NULL;
}