【发布时间】:2018-04-06 06:45:07
【问题描述】:
因此,对于我的学校课程,我只需从以下格式的文本文件中读取整数列表,第一行表示整数的数量。然后对整数进行排序(它们在 txt 文件中未排序),然后求均值。我只是试图从我一直在使用的测试 .txt 文件中将整数读入数组。
9
1
3
2
4
...
#include<stdio.h>
#include<stdlib.h>
int amtValues;
int *values;
float find_median (int* values){
if(amtValues%2==0){
return ((values[amtValues/2] + values[amtValues/2 -1]) /2.0);
}
else
return values[amtValues/2];
}
int main(int argc, char **argv){
//open the file, copy the data from the file, and determine the number of values
//open the filestream
FILE* fp = fopen(argv[1], "r");
if(!fp){
printf("error reading file\n");
return 1;
}
//determine the number of values
char *lineOne;
if(fgets(lineOne, 80, fp)!=1)
puts (lineOne);
lineOne++;
amtValues = atoi(lineOne);
printf("\nThe amount of values is: %d\n",amtValues);
/*allocate memory for values array, and copy the values from file.*/
values = (int*)malloc(amtValues*sizeof(int));
int i=0;
while(!feof(fp)){
int curNum;
fscanf(fp, "%d", &curNum);
values[i] = curNum;
i++;
}
fclose(fp);
for(i=0; i<amtValues; i++)
printf("\n%d");
}
这就是我目前要做的事情,我收到一个错误,说segmentationFault(core Dumped)。我是 C 新手,所以我真的不确定这意味着什么。
【问题讨论】:
-
哪一行导致了这个问题?编译器显示哪一行?
-
糟糕的代码。部分依赖于参数,主要是全局变量。
标签: c file dynamic-arrays