gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:11:18 25 4
gpt4 key购买 nike

我收到警告:

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 数组需要分配。但我认为它进入了我的代码。有人知道这里发生了什么吗?

最佳答案

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

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;
}

然后警告就会消失。

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

关于c - 在此函数中使用未初始化的二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58647362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com