簡體   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