#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void stringReverse(char* s){
char tmp;
int i = 0;
int j = (strlen(s)-1);
while(i>=j){
tmp = s[i];
s[i] = s[j];
s[j] = tmp;
i++;
j--;
}
}
int main(int argc, char* argv[]){
FILE* in; /* file handle for input */
FILE* out; /* file handle for output */
char word[256]; /* char array to store words from the input file */
/* checks that the command line has the correct number of argument */
if(argc !=3){
printf("Usage: %s <input file> <output file>\n", argv[0]);
exit(EXIT_FAILURE);
}
/* opens input file for reading */
in = fopen(argv[1], "r");
if(in==NULL){
printf("Unable to read from file %s\n", argv[1]);
}
/* opens ouput file for writing */
out = fopen(argv[2], "w");
if(out==NULL){
printf("Unable to read from file %s\n", argv[2]);
exit(EXIT_FAILURE);
}
/* reads words from the input file and reverses them and prints them on seperate lines to the output file */
while(fscanf(in, " %s", word) != EOF) {
stringReverse(word);
fprintf(out, "%s\n", word);
}
/* closes input and output files */
fclose(in);
fclose(out);
return(EXIT_SUCCESS);
}
我一直收到段错误(核心转储)错误 . 我究竟做错了什么?我的out文件也是空的,不应该发生 .
我的意见是
abc def ghij
klm nopq rstuv
w xyz
输出应该是
cba
fed
jihg
mlk
qpon
vutsr
w
zyx
1 回答
当然你应该花一些时间学习使用
gdb
和valgrind
. 至于代码,不应该是while(i<=j)
而不是第9行的while(i>=j)
?Explanation:
Barmar和loginn之间的讨论实际上很好地解释了为什么分段错误发生在这里 . 逻辑
while(i>=j)
错误,但您在输入文件中赢得了样本输入中的't get a segmentation fault for this unless you have a single character (such as ' w' . 为什么单个字符输入会导致分段错误?因为那时你开始你的循环,i = 0和j = 0,它满足循环条件,然后进入i = 1和j = -1,这也满足不正确的循环条件 . 此时,尝试访问无效地址(s[-1]
)将导致分段错误 .如果输入文件中没有任何单个字符,那么程序将只运行并打印输出文件中的单词 . 它不会反转任何单词,因为代码不会因为错误的条件而进入反转的while循环 . 但它也不会导致任何分段错误 .
我希望我已经解释得很好 .