我需要一个函数来从文件中读取成绩(整数)并返回一个动态分配的数组来存储它们。
这是我尝试过的:
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
谁能告诉我我做错了什么?
最佳答案
问题:以下代码:
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);
关于c - 将文件中的数字读入动态分配的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19093224/