简体   繁体   English

分割错误-矩阵转置-C

[英]Segmentation Fault - Transpose of a Matrix - C

I have a segmentation fault error on the following code: 我在以下代码上出现细分错误错误:

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;
}

Apparently, the program gives me the segmentation fault message when it reaches this line: 显然,该程序在到达以下行时会给出分段错误消息:

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

Please, if anyone can help me, I would appreciate. 请,如果有人可以帮助我,我将不胜感激。 Also, sorry for eventual bad english (I'm from Brazil) 另外,对您最终的英语不好也感到抱歉(我来自巴西)

Try: 尝试:

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;
}

Paul Draper, you almost right. 保罗·德雷珀(Paul Draper),您说得对。 I think, correct code should look like this: 我认为,正确的代码应如下所示:

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;
}

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

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