我在以下代码中出现了分段错误错误:
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++) {
请,如果有人可以帮助我,我将不胜感激。 还有,抱歉最终的英语不好(我来自巴西)
答案 0 :(得分: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;
}
答案 1 :(得分: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;
}