Format specifier %s
in
fprintf(outfile, "%s", inputline[j]);
expects a char *
variable, but you are actually passing a char
(j th element of inputline
array).
The reason why a segmentation fault occurs is that fprintf
tries to "access" the memory location poited by the passed character. And since it will be very likely an invalid address the OS will complain about the attempt to access the memory outside the space assigned to your application.
You can either print to file char by char, keeping the for-loop and using %c
format
for(int j=0; j<20; ++j)
{
fprintf(outfile, "%c", inputline[j]);
}
or print the whole string keeping the %s
format, passing the whole array and getting rid of the for-loop:
fprintf(outfile, "%s", inputline);
Note: in the first case 20 characters will be written, anyway. In the second case "length+1" characters because of the string terminator ''
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…