c - 函数之间的文件指针上的 SegmentFault

标签 c pointers segmentation-fault function-pointers

在你说之前,是的,我已经检查了几乎所有其他帖子,没有一个有效。

我的程序已经好几个小时都给我一个段错误,但没有任何解决办法。我调试它到我发现它在文件指针中的地步。据我所知,这是因为我在“makeArray”函数或文件关闭语句中使用文件指针的方式。我真的不明白它为什么不起作用,因为我使用上一个程序作为引用,它运行得很好,但这个不行。

#include <stdio.h>
#include <stdlib.h>

#define ROWS 12
#define COLS 8

void makeArray(FILE*, int [][COLS]);
int getScore(int [][COLS], int, int);
int getMonthMax(int [][COLS], int);
int getYearMax(int [][COLS]);
float getMonthAvg(int [][COLS], int);
float getYearAvg(int [][COLS]);
int toursMissed(int [][COLS]);
void displayMenu();
int processRequest(int [][COLS], int);
void printArray(int [][COLS]);

int main(){

    int scoresArray[ROWS][COLS];
    int choice, constant = 0;

    FILE* inputPtr;
    inputPtr = fopen("scores.txt", "r");
    makeArray(inputPtr, scoresArray);
    fclose(inputPtr);

    while(constant == 0){
        displayMenu();
        scanf("%d", &choice);
        processRequest(scoresArray, choice);
    }
    return 0;
}

void makeArray(FILE* inputPtr, int scoresArray[][COLS]){
    int i, j;
    for(i = 0; i < ROWS; i++){
        for(j = 0; j < COLS; j++){
            fscanf(inputPtr, "%d", &scoresArray[i][j]);         
        }
    }
    return;
}

我试过将文件指针移动到代码中的每个不同位置,但没有任何效果。我不一定要你只给我答案,但我想解释为什么它会在这个特定的代码中发生,因为我检查过的所有其他帖子和他们的结果与我的不匹配。

输入文件也是

26 35 25 92 0 6 47 68 26 72 67 33 84 28
22 36 53 66 23 86 36 75 14 62 43 11 42 5
14 58 0 23 30 87 80 81 13 35 94 45 1 53
14 55 46 19 13 0 25 28 66 86 69 0 81 15
55 60 26 70 22 36 15 67 62 16 71 7 29 92
84 37 2 30 7 5 4 50 0 67 2 53 69 87
8 23 74 58 86 0 78 88 85 12 1 52 999 

最佳答案

我想知道你的大学编译器是否对输入文件很挑剔 - 你能从你的输入文件的副本中删除所有新行并尝试使用复制的修改后的输入文件运行 --- 所以它只是一个数字流 - -- 看看这是否解决了问题...

........根据我对 scanf 和 fscanf 的经验,如果输入不完全按照你在格式部分所说的那样运行,这些函数可能会有点脆弱 - 这里“%d”不告诉 fscanf 关于换行符....

关于c - 函数之间的文件指针上的 SegmentFault,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38556748/

相关文章:

c - 我如何知道外部 DLL 是否进入函数?

c - wchar_t 读取

c/fork/signals/关闭不同进程中打开的套接字的最佳实践

C++ 进程因状态 3 混淆而终止

c++ - 成功调用析构函数或调用 empy 析构函数后出现段错误。 C++

c - 如何检查输入是否为 C 中的数字?

c - C语言中的结构体

C 将字符串拆分为单个单词并将单个单词保存在数组中

c - strtok_r 上的段错误

c - 使用 fscanf() 读取一行