我的代码分段错误

  • 本文关键字:错误 分段 代码 c
  • 更新时间 :
  • 英文 :


我对C很陌生,但我不知道为什么会出现这个错误。我知道分段故障是由于超出了我的范围,但我不知道我在哪里。

这是我的代码

#include <stdlib.h>
#include <stdio.h>
int** totalMatrix(int numRows, int numCols){
    int** firstMatrix;
    int** secondMatrix;
    int** sumMatrix;
    int row, col;
    printf("Enter Matrix An");
    firstMatrix = (int**)malloc(numRows * sizeof(int*));
    for(row = 0; row < numRows; row++){
        firstMatrix[row] = (int*)malloc(numCols * sizeof(int));
    }
    for(row = 0; row < numRows; row++){
        for(col = 0; col < numCols; col++){
            scanf("%d", &firstMatrix[row][col]);
        }
    }
    printf("Enter Matrix Bn");
    secondMatrix = (int**)malloc(numRows * sizeof(int*));
    for(row = 0; row < numRows; row++){
        secondMatrix[row] = (int*)malloc(numCols * sizeof(int));
    }
    for(row = 0; row < numRows; row++){
        for(col = 0; col < numCols; col++){
            scanf("%d", &secondMatrix[row][col]);
        }
    }
    printf("A + B =n");
    sumMatrix = (int**)malloc(numRows * sizeof(int*));
    for(row = 0; row < numRows; ++row){
        for(col = 0; col < numCols; ++col){
            sumMatrix[row][col] = firstMatrix[row][col] + secondMatrix[row][col];
            printf("%d ", sumMatrix[row][col]);
        }
        printf("n");
    }
    return 0;
}

void delete_matrix(int numRows, int** matrix){
    int row;
    for(row = 0 ; row < numRows; ++row){
        free(matrix[row]);
    }
    free(matrix);
}
int main(){
    int numRows, numCols;
    int** matrix;
    printf("Please Enter the number of rows: ");
    scanf("%d", &numRows);
    printf("Please Enter the number of cols: ");
    scanf("%d", &numCols);
    matrix = totalMatrix(numRows, numCols);
    delete_matrix(numRows, matrix);
    return 0;
}

它工作,但崩溃

提前谢谢。

对于firstMatrixsecondMatrix,您正确地malloc外部维度,然后在循环中malloc所有内部维度。

由于某些原因,对于sumMatrix,您只需要malloc'd外部维度它存储的所有指针都未初始化,但您正在取消对它们的引用。

请注意,当我说"正确"时,我会松散地使用这个词:这是一个不必要的动态分配的lot!更喜欢一个大的分配。可以在单个内存块上映射二维索引。这样也可以避免这个错误

此外,函数总是返回0。这是一个空指针。因此,当您在main中使用它并将其传递给delete_matrix时,这是没有意义的。我会完全去掉返回,并将delete_matrix调用移动到totalMatrix的底部(argh!函数命名不一致!),因为您实际上需要执行三次;每个矩阵一次。

最新更新