0

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.

4
  • Unless I'm missing the point of this function it should have no memory allocations at all. You're swapping rows, and in this case that means two pointers to two rows simply need to be swapped. Bulk memory copying is unneeded. Commented Mar 15, 2015 at 19:47
  • @Kheldar because of your edit reason: No, that won´t run at all. Commented Mar 15, 2015 at 19:55
  • @deviantfan my view is that modifying the code in the question is a bad idea, because it transforms answers to the question into "answers to another situation". If you still feel your position is correct, feel free to roll it back ^^ Commented Mar 15, 2015 at 19:58
  • @Kheldar Yes, that´s ok and I think so too Commented Mar 15, 2015 at 20:00

1 Answer 1

4

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

The speed difference between the former and the latter cannot be overstated. Further, even the former can be done with no allocations, a single temporary double and one loop, though I cannot imagine why anyone would do so when the latter is O(1) vs O(n).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.