【问题标题】:Reading matrix from text file c从文本文件 c 中读取矩阵
【发布时间】:2020-12-29 22:46:46
【问题描述】:

使用 gcc 进行编译时,我收到错误消息“分段错误(核心转储)”,但我找不到访问超出限制内存的点。我什至试图只部分填充矩阵,但在我成功地从文件中读取所有值之后,我得到了相同的错误消息。读取最后一个元素后触发错误

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

#define NR 4
#define NC 8
#define FILENAME "../debug.log"

int ndominanti(int [][NC], int);

int main(int argc, char * argv[]){
    
    int info[NR][NC];
    FILE * pf;
    int i, j, ris;

    if(pf = fopen(FILENAME, "r")){

        for(i = 0; i < NR; i++)
            for(j = 0; j < NC; j++)
                fscanf(pf, "%d", &info[i][j]);
    /* this is where the error occurs */

        fclose(pf);

        ris = ndominanti(info, NR);
        printf("ris: %d\n", ris);
    }else
        printf("Errore apertura file %s\n", FILENAME);

    return 0;
}

int ndominanti(int info[][NC], int nrighe){
    int i, j, k, h;
    int curr, ndom, nrighedim, ncoldim;
    int isdom;

    nrighedim = nrighe - 1;
    ncoldim = NC - 1;
    ndom = 0;
    for(i = 0; i < nrighedim; i++)
        for(j = 0; i < ncoldim; j++){
            curr = info[i][j];
            isdom = 1;
            for(k = i + 1; k < nrighe && isdom; k++)
                for(h = j + 1; h < NC && isdom; h++)
                    if(curr <= info[k][h])
                        isdom = 0;
            if(isdom)
                ndom++;
        }

    return ndom;
}

这是 debug.log 文件的内容,每行由 CRLF 分隔,单个元素由单个空格分隔,最后有一个 CRLF

5 9 2 4 1 7 2 4
3 5 6 2 5 6 1 2
1 3 4 7 8 8 3 0
1 3 5 6 7 8 2 1

【问题讨论】:

  • 编译时出现分段错误?
  • 你的意思是“for(j = 0; j
  • for(j = 0; i &lt; ncoldim; j++) -> for(j = 0; j &lt; ncoldim; j++)
  • 提示:使用调试器。似乎您实际上并不知道触发段错误的确切行。调试器可以立即为您提供该信息,也可以用于检查变量。
  • @Peter-ReinstateMonica - 这个评论应该是个玩笑吗?有一条用另一种语言输出的消息。

标签: c matrix segmentation-fault text-files


【解决方案1】:

我很抱歉,但我无法弄清楚这个问题,无论如何这让我发疯了,我只接受了这个

for(j = 0; i < ncoldim; j++) -> for(j = 0; j < ncoldim; j++)

谢谢@kaylum

我没有检查函数,因为我认为问题出在 main 内部,因为在代码中标记的点之后我无法执行任何命令(在我调用函数之前)

【讨论】:

    猜你喜欢
    • 2015-06-21
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多