【发布时间】:2022-11-14 21:29:32
【问题描述】:
我正在尝试创建一个函数,将文本文件中的所有数字读取到一个数组中,其中文件的每一行都有一个数字,例如:
57346
40963
24580
98307
98312
32777
10
16392
16396
...
我的函数确实分配了必要的大小来存储值,但是存储的值是随机值和 0,它们不在我的文本文件中。输出例如:
0
0
296386
0
-485579776
-653048057
584
0
2095946880
...
这是我的代码:
typedef struct set{
void** values;
int size;
}Set;
int checkSize(FILE* file) {
int counter = 0;
char chr;
chr = getc(file);
while (chr != EOF) {
if (chr == '\n') {
counter = counter + 1;
}
chr = getc(file);
}
return counter;
}
Set* readSet(FILE* file){
Set* new = malloc(sizeof(Set));
new->size = checkSize(file);
new->values = malloc(sizeof(void*)*new->size);
int arrayAux[new->size];
int i = 0, n;
while(i < new->size) {
fscanf(file, "%ld", &arrayAux[i]);
new->values[i] = arrayAux[i];
i++;
}
//loop to remove the first three lines of the file, wich are the number of values in the file,
//the biggest value of the file and the division between the number of values and the biggest value
for(i = 0; i < 3; i++) {
new->values[i] = new->values[i + 1];
new->size--;
}
for (i = 0; i <= new->size; i++) {
printf("%d\n", new->values[i]);
}
return new;
}
我怎样才能解决这个问题?提前感谢您的帮助。
【问题讨论】:
-
为什么
void**而不是int *用于values字段?由于您存储的是int值而不是指针。另外,请显示打印结果的代码。也就是说,提供一个完整的minimal reproducible example 来重现问题。 -
您需要在调用
checkSize后rewind文件,因为文件指针将位于文件末尾。 -
checkSize读取到文件末尾,因此fscanf没有任何内容可供读取。检查返回值,以便知道它是成功还是失败。chr也应该是int。 -
在调试期间您应该调查的一件事是问题是否是 (1) 值被正确读取并存储到数组中,但是当您尝试打印它们时出现损坏;或 (2) 从一开始就没有正确读取这些值。这将告诉您需要关注程序的哪一部分。
-
"%ld"需要一个指向long变量的指针。但是您提供的是&arrayAux[i],它是指向int的指针。