简体   繁体   中英

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. I am just swapping rows in the array and need to return the modified array to the main function.

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.
And, as WhozCraig pointed out, in a double **matrix where each row is allocated separately, you could just switch the row pointers.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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