以下代码出现段错误:
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++) {
拜托,如果有人能帮助我,我将不胜感激。 另外,很抱歉最终英语不好(我来自巴西)
最佳答案
Paul Draper,你几乎是对的。我认为,正确的代码应该是这样的:
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;
}
关于c - 段错误 - 矩阵转置 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19757081/