【问题标题】:Segmentation Fault - Transpose of a Matrix - C分割错误 - 矩阵的转置 - C
【发布时间】:2013-11-03 19:30:43
【问题描述】:

以下代码出现分段错误错误:

struct matrix {
int nl, nc ;
int** mat ;
};

 Matrix* initMatrix (int nlines, int ncol) {
    struct matrix* mat ;
    mat = (struct matrix*)malloc(sizeof(struct matrix)) ;
    mat->nl = nlines ;
    mat->nc = ncol ;
    int i ;
    mat->mat = (int **)malloc((mat->nl)*sizeof(int *)) ;
    for (i=0;i<(mat->nl); i++) {
        mat->mat[i] = (int*)malloc((mat->nc)*sizeof(int)) ; 
    }
    return mat ;
}   

Matrix* transp (Matrix* mat) {
    int i, j;
    int linesTrp = mat->nc ;
    int colTrp = mat->nl ;
    Matrix* trp = initMatrix (linesTrp, colTrp) ;   
    for (i=0; i<(linesTrp); i++) {
        for (j=0; j<(colTrp); j++) {        
            trp->mat[j][i] = mat->mat[i][j] ;
        }
    }
    return trp;
}

显然,程序在到达这一行时给了我分段错误消息:

for (j=0; j<(colTrp); j++) {

如果有人可以帮助我,我将不胜感激。 另外,很抱歉最终英语不好(我来自巴西)

【问题讨论】:

    标签: c matrix segmentation-fault


    【解决方案1】:

    保罗·德雷珀,你几乎是对的。我认为,正确的代码应该是这样的:

    Matrix* transp (Matrix* mat) {
        int i, j;
        int linesTrp = mat->nc ;
        int colTrp = mat->nl ;
        Matrix* trp = initMatrix (linesTrp, colTrp) ; // was correct originally
        for (i=0; i< colTrp; i++) {                   // edited to correctly address mat->mat
            for (j=0; j< linesTrp; j++) {             // edited to correctly address mat->mat
                trp->mat[j][i] = mat->mat[i][j] ; //edited
            }
        }
        return trp;
    }
    

    【讨论】:

    • 是的,现在它真的很完美!谢谢!
    【解决方案2】:

    试试:

    Matrix* transp (Matrix* mat) {
        int i, j;
        int linesTrp = mat->nc ;
        int colTrp = mat->nl ;
        Matrix* trp = initMatrix (colTrp, linesTrp) ; //edited 
        for (i=0; i<(linesTrp); i++) {
            for (j=0; j<(colTrp); j++) {        
                trp->mat[j][i] = mat->mat[i][j] ; //edited
            }
        }
        return trp;
    }
    

    【讨论】:

    • 对不起,我已经做了 trp->mat[j][i] = mat->mat[i][j];带有 [1][i] 的行是我为试图找到错误所做的事情
    • @CleissonSantosGuterres,它仍然应该在某些矩阵上崩溃。看我的回答。
    猜你喜欢
    • 2016-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多