问题描述
int main( int argc, char** argv) {
FILE *inFilePtr = fopen(*(argv + 1), "r");
char *rawdata = malloc(sizeof(char) * 100);
float *ary = malloc(sizeof(float) * 50);
int counter = 0;
float averageAns;
int count = 0;
while (count < 1 ){
//fgets(rawdata, 50, inFilePtr); //I have tried both
fscanf(inFilePtr, "%s", rawdata);
*(ary + counter) = atof(strtok(rawdata, ","));
counter++;
*(ary + counter ) = atof(strtok(rawdata, NULL));
counter++;
*(ary + counter) = atof(strtok(rawdata, NULL));
counter++;
count++;
}
我终其一生都无法弄清楚为什么我总是遇到段错误.即使没有循环,它也会出现段错误(计数 < 1 只是为了看看我是否可以通过一次).
I cannot for the life of me figure out why I keep getting a seg fault. It will seg fault even without the loop (the count < 1 was just to see if I could make it through once).
它不适用于 fgets()、fscanf().当我将 fgets 中的流更改为 (stdin) 时,它会出现段错误,我提到这一点是因为我认为文件 * 是问题,但现在我认为不是.我在数据文件"和,"中设置了分隔符.
It will not work with fgets(), fscanf(). It seg faults when I change the stream in fgets to (stdin), and I mention this because I assumed the file * was the issue, but now I do not think it is. I have made the delimiter in my data file " " and ",".
如果有人知道我做错了什么,我将不胜感激.
If anyone know's what I did wrong, I would appreciate it.
推荐答案
您对 fscanf
的调用肯定会失败,因为您没有提供输出参数.它应该看起来像:
Your call to fscanf
is guaranteed to fail, as you have not provided an output argument. It should look like:
fscanf(inFilePtr, "%s", rawdata);
您对 strtok
的调用也无效.要继续标记相同的字符串,strtok
的 first 参数应该是 NULL
;strtok
期望第二个参数仍然是有效的字符串.
Your calls to strtok
are also invalid. To continue tokenising the same string, the first argument of strtok
should be NULL
; strtok
expects the second argument to still be a valid string.
这些问题中的每一个都会自行导致段错误.为了简化您将来的调试,我建议您使用调试器并在您正在调试的语句之后设置断点,或者注释掉您可能期望出现段错误的其他行(如果您的代码通常包括对字符串执行任何操作的任何内容)处于脆弱状态.
Each of these issues would cause a segfault on their own. To ease your debugging in future, I would suggest either using a debugger and setting a breakpoint after the statement you are debugging, or commenting out other lines which you might expect to segfault (which typically includes anything that does anything with strings, if your code is in a fragile state.
另外,就风格而言,
*(ary + counter)
正常写
ary[counter]
这篇关于c 分段错误 fgets的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!