在此函数中使用未初始化的二维数组

2D array is used uninitialized in this function

我收到警告:

matrixResult' is used uninitialized in this function [-Wuninitialized]

在此函数中:

int **addMatrices(int **matrixA, int **matrixB, int *rows, int *cols) {
    int **matrixResult = initializeMatrix(matrixResult, rows, cols);
    for (int i = 0; i < *rows; i++)
        for (int j = 0; j < *cols; j++)
            matrixResult[i][j] = matrixA[i][j] + matrixB[i][j];

    return matrixResult;
}

但它正在这里初始化:

int **initializeMatrix(int **matrix, int *rows, int *cols) {
    matrix = (int **)malloc((*rows) * sizeof(int*));
    checkNullPointer(matrix);
    for(int i = 0; i < *rows; i++) {
        matrix[i] = (int *)calloc(*cols, sizeof(int));
    }

    return matrix;
}

不是吗?我试图找到答案,但每个人都说 2D array needs to get allocated 。但我认为它进入了我的代码。有人知道这里发生了什么吗?

您不必要地传递了未初始化的指针,并将其用作局部变量。如果您删除它并使用真正的局部变量,如下所示:

int **initializeMatrix(int *rows, int *cols) {
    int **matrix = malloc((*rows) * sizeof(int*));
    checkNullPointer(matrix);
    for(int i = 0; i < *rows; i++) {
        matrix[i] = calloc(*cols, sizeof(int));
    }

    return matrix;
}

int **addMatrices(int **matrixA, int **matrixB, int *rows, int *cols) {
    int **matrixResult = initializeMatrix(rows, cols);
    for (int i = 0; i < *rows; i++)
        for (int j = 0; j < *cols; j++)
            matrixResult[i][j] = matrixA[i][j] + matrixB[i][j];

    return matrixResult;
}

然后警告应该消失。

旁白:我还删除了不必要的转换。