【发布时间】:2020-09-14 23:58:30
【问题描述】:
当我运行以下代码时,我在fprintf(outfile, "%s", inputline[j]); 收到一个“分段错误”。
我无法理解错误的原因。我对 C 比较陌生,有人可以帮我解决错误吗?
void test(char *inputline) {
FILE *outfile = fopen("results.txt", "w");
if (!outfile) {
perror("Error while opening file: ");
} else {
for (int j = 0; j < 20; ++j) { // I only want to be write the first 20 characters to the file that is why I have the iteration till only 20 and added [j], is that correct way to do it?
fprintf(outfile, "%s", inputline[j]);
}
}
}
//Function call
...
char inputline[40] = "hello world 123 456"; //passed to the function above
test(inputline);
【问题讨论】:
-
您将一个字符 (inputline[j]) 传递给 fprintf,但格式说明符需要一个字符串 (char *)。
-
您为需要
char*指针的fprintf提供了char。需要地址的char的低值在取消引用时可能会出现段错误。你需要"%c" -
倒数第二行缺少分号,函数永远不会关闭。
-
提示:更改示例代码完全不加备注帮助不大
-
@Anna 好的,但请发布真实代码,Minimal Reproducible Example,这是显示问题的最短完整代码。
标签: c segmentation-fault printf