0

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)

4

2 回答 2

0

尝试:

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;
}
于 2013-11-03T19:32:37.810 回答
0

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

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;
}
于 2013-11-03T19:46:37.813 回答