0

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?

1
  • You can use the const-keyword when passing your argument. But you'll need to be careful when passing your pointer. There are two ways of const-correctness: Retaining the pointer and retaing the value it points to. If you want to be sure, try dontModify(M const * const pointerM). Consider this. Commented Feb 15, 2013 at 8:24

2 Answers 2

3

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` */

    ...
}
Sign up to request clarification or add additional context in comments.

4 Comments

Or even simpler: pass the matrix by value to the function
@ring0 That would require wrapping it in a struct, though.
@ring0 I'm sorry, pardon my ignorance. How would you do this?
@user1505713 It's not really possible, arrays are passed by reference and can't really be passed by value.
0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.