c - 段错误 - 矩阵转置 - C

标签 c matrix segmentation-fault

以下代码出现段错误:

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/

相关文章:

c - 我得到 "Invalid Initializer",我做错了什么?

c - 如何在 HWND 中包含 Windows Word 文档?

r - 在 R 中创建某个矩阵

c - 初始化结构体 C 中的变量矩阵

C编程分段故障链表程序

C++类,调用成员函数时出现段错误

c - C 中的 fscanf 段错误

c - 将文本读入 C。出现错误的执行错误

matlab - 如何在 MATLAB 中将张量的维度折叠为标量

c - 编写符合 POSIX 标准的内核