user1505713
user1505713

Reputation: 607

Passing pointer to function WITHOUT modifying argument?

I have a matrix M[2][2] and want to make a call to function dontModify(M) that will play around with the elements of M but not change them. Something like:

dontModify(M):
   swap off-diagonal elements;
   take determinant of M;
   return determinant;

...but without having the function change M in the process. Anything convenient that would accomplish this?

Upvotes: 0

Views: 111

Answers (2)

Some programmer dude
Some programmer dude

Reputation: 409136

Create a local copy of the matrix inside the function, one that you can do whatever you want with.


int some_function(int matrix[2][2])
{
    int local_matrix[2][2] = {
        { matrix[0][0], matrix[0][1] },
        { matrix[1][0], matrix[1][1] },
    };

    /* Do things with `local_matrix` */
    /* Do _not_ use `matrix` */

    ...
}

Upvotes: 3

sergeyk555
sergeyk555

Reputation: 64

Frankly speaking do not undestand your problem. You are working with matrix, so it will be passing via pointer to function. So just create a copy of your matrix, play with it, destroy the copy before returning back. In case this call will be very frequent, you can try to save some time and just work in-place, just do not forget to swap off-diagonal elements back before return.

Upvotes: 0

Related Questions