我有一个看起来像这样的函数:
void swapRows(int row_1, int row_2, double **matrix, int n, int m)
{
double arrTemp = (double *)malloc(m * sizeof(double));
int i;
for(i = 0; i < m; i++)
{
arrTemp[i] = matrix[row_1][i];
*matrix[row_1][i] = matrix[row_2][i];
}
for(i = 0; i < m; i++)
{
*matrix[row_2][i] = arrTemp[i];
}
}
我尝试使用两颗星和一颗星取消对数组的引用,但无法弄清楚。我不想将它存储在另一个数组中并通过 double 函数返回它,我需要从这个 void 函数返回它。我只是交换数组中的行,需要将修改后的数组返回给主函数。
最佳答案
只要您只是更改数组中的值,就不需要做任何特殊的事情。删除函数中的所有 *
并访问数组,就像您不想“返回”它一样。
void swapRows(int row_1, int row_2, double **matrix, int n, int m){
double arrTemp = (double *)malloc(m * sizeof(double));
int i;
for(i = 0; i < m; i++){
arrTemp[i] = matrix[row_1][i];
matrix[row_1][i] = matrix[row_2][i]; //no *
}
for(i = 0; i < m; i++){
matrix[row_2][i] = arrTemp[i]; //no *
}
}
不相关的问题,您在这里缺少一个免费的 malloc。
而且,正如 WhozCraig 指出的那样,在每行单独分配的 double **matrix
中,您只需切换行指针即可。
void swapRows(int row_1, int row_2, double **matrix, int n, int m){
double *tmp = matrix[row_1];
matrix[row_1] = matrix[row_2];
matrix[row_2] = tmp;
}
关于c - 从 C 中的 void 函数返回二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29065307/