c - 使用 fopen 时出现段错误

标签 c segmentation-fault fopen

我从以下代码的第二行收到一个段错误:

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/

相关文章:

无法将数组中的数字更改为我想要的数字

c - 必须将函数 sscanf 分配给变量,否则会出现奇怪的行为

c - 插入哈希表时出现段错误

c - 如何在C程序中从另一个txt查找我们想要的字符?

C++ 在 Linux 上编写 UTF-8

c - 二十一点程序的多个问题(发牌、错误、命中)

c - 什么是文件序列号?

c++ - 这个段错误的根源是什么?

c - fscanf 返回段错误,而我的文件指针不为空

c - 尝试按字节读取图像字节时出现段错误 11