I'm getting a warning:
matrixResult' is used uninitialized in this function [-Wuninitialized]
in this function:
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;
}
But its is getting initialized here:
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;
}
isn't it? I was trying to find an answer, but everyone just says that 2D array needs to get allocated . But I think that it gets in my code. Anyone has a clue what's going on in here?
You have passed the uninitialised pointer, unnecessarily, and used it as a local variable. If you remove that and use a true local variable, like this:
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;
}
then the warning should go away.
Aside: I also removed the unnecessary casts.