我从下面的代码的第二行接收段错误:段错误而使用的fopen
FILE *output = NULL;
output = fopen("./output2.txt", "w+");
我不认为这是某种形式的破坏内存错误的,因为当我改变w +来河它运行时没有段错误。此外,它似乎创建该文件之前它segfaults。
编辑:原来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);
}
+0
错误实际上是您的'fopen'之后的第一个'fprintf'。 '%s'格式说明符需要一个'char *',并且你传递了一个'char'值('* header'),它试图将其解释为一个地址并导致段错误。 –
+0
我知道这不是因为我在代码中有一个测试printf(我在发布之前删除了它),这是在fopen之后和fprintf之前的。 –
+1
请用'printf'显示测试代码并重新运行测试。 'fopen'很好,但是'fprintf'最明显的不是。或者更好的是,注释掉'fopen'后面的'fprintf',看看会发生什么。 –