简体   繁体   English

从C中的void函数返回2d数组

[英]Returning 2d array from void function in C

I have a function that looks like this: 我有一个看起来像这样的函数:

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

}

I tried dereferencing the array using two stars and a single star but can not figure it out. 我尝试使用两颗星和一颗单星对数组进行解引用,但无法弄清楚。 I don't want to store it in another array and return it VIA a double function, I need to return it from this void function. 我不想将其存储在另一个数组中并通过double函数返回它,我需要从这个void函数中返回它。 I am just swapping rows in the array and need to return the modified array to the main function. 我只是交换数组中的行,需要将修改后的数组返回给main函数。

As long as you´re only changing the values in the array, you don´t need to do anything special. 只要您仅更改数组中的值,就无需执行任何特殊操作。 Remove all * within the function and access the array like you don´t want to "return" it. 删除函数中的所有*并访问数组,就像您不想“返回”它一样。

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

Unrelated problem, you´re missing a free to this malloc here. 无关的问题,您在这里缺少此malloc的免费版本。
And, as WhozCraig pointed out, in a double **matrix where each row is allocated separately, you could just switch the row pointers. 而且,正如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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM