繁体   English   中英

从文本文件 c 中读取矩阵

[英]Reading matrix from text file c

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

#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; i < ncoldim; j++) -> for(j = 0; j < ncoldim; j++)

谢谢@kaylum

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM