我从以下代码的第二行收到一个段错误:
FILE *output = NULL;
output = fopen("./output2.txt", "w+");
我不认为这是某种损坏的内存错误,因为当我将 w+ 更改为 r 时。它运行时没有段错误。此外,它似乎在出现段错误之前就创建了文件。
编辑:事实证明 mrbatch 是正确的
我所有的代码供引用:
void writeFile(const char *header, int numRows, int numCols, int **grades, const char *outFile)
{
printf("writefile success\n");
int i, j;
FILE *output = NULL;
output = fopen("./output2.txt", "w+"); // ERROR HERE (I was wrong, keep reading)
printf("testestestsetsete\n\n\n"); //based off the commenters, this code
//IS reached but is never printed
fprintf(output, "%s", *header); //commenters stated error is here
//*header should be header
fprintf(output, "%d %d\n", numRows, numCols); //output the number or rows and columns at the second line
//output each grades(scores) in the processed 2D array grades
for(i = 0; i < numRows; i ++ ) { //loop through all rows
for( j = 0; j < numCols; j ++ ) //loop through all columns in the i row
{
if( j < numCols - 1 )
fprintf(output, "%d ", grades[i][j]);
else
fprintf(output, "%d\n", grades[i][j]);
//printf("\"%d\" ", score);
}
//printf("\n");
}
fclose(output);
最佳答案
错误实际上是在你的fopen
之后的第一个fprintf
。
fprintf(output, "%s", *header); //output the same header
%s
格式说明符需要一个 char *
而您传递了一个 char
值 (*header
)它试图将其解释为地址并导致段错误。
关于c - 使用 fopen 时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22240817/