0

Summary

It is just a doubt that came when studying about pointers, can I swap two matrixes using a function without needing to swap element by element in it?

I've created 2 matrixes dynamically, using malloc, and declared its elements` values in main(). So, I could swap like this:

(Swapping element by element)

void swapMatrix(int** a, int** b){
    for(int i = 0; i< row; i++){
        for(int j = 0; j< col; j++){
            int tmp = a[i][j];
            a[i][j] = b[i][j];
            b[i][j] = tmp;
        }
    }
}
...
int main() {
...
print(M1);
swapMatrix(M1, M2);
print(M1);
...

(Swapping row by row)

void swapMatrix(int** a, int** b){
    int* tmp = *a;
    *a = *b;
    *b = tmp;
    for (int i = 0; i<col; i++){
        int* tmp = *(a+i);
        *(a+i) = *(b+i);
        *(b+i) = tmp;
    }
}
...
int main() {
...
print(M1);
swapMatrix(M1, M2);
print(M1);
...

The Attempts

But is there a way to just change the matrix pointer to pointer address? I've attempted the following codes:

I)

void swapMatrix(int** a, int** b){
    int** tmp = a;
    a = b;
    b = tmp;
}
...
int main() {
...
print(M1);
swapMatrix(M1, M2);
print(M1);
...

It compiled but when I verified its elements, none of them really swapped

II)

void swapMatrix(int*** a, int*** b){
    int*** tmp = a;
    a = b;
    b = tmp;

...
int main() {
...
print(M1);
swapMatrix(&M1, &M2);
print(M1);
...

Again, it compiled but when I verified its elements, none of them really swapped.

How should I implement the function in order to swap the entire matrix just changing a pointer to pointer address? Is it possible? Actually, I don't really understand why the I) attempt didn't work. I would really appreciate if you could explain the details.

Benuck
  • 19
  • 5
  • Possible duplicate of [Is it possible to swap the addresses of two variables?](https://stackoverflow.com/questions/27458825/is-it-possible-to-swap-the-addresses-of-two-variables) – Israel Figueirido May 22 '19 at 00:05

3 Answers3

0

No, that's not possible. You can't choose the addresses of variables or modify them either.

0

If M1 and M2 are pointers to your matrices then swapMatrix in option 1 would work except the pointer operations are a bit off. You need to swap the value pointed at by a and b (i.e. the address of each matrix) but you're just swapping the value of a and b(i.e. changing which pointer to matrix your local parameter is pointing to). Try something like:

void swapMatrix(int** a, int** b){
    int* tmp = *a;
    *a = *b;
    *b = tmp;
B-Mo
  • 11
  • 2
0

Approach 3 is really close:

void swapMatrix(int*** a, int*** b){
    int** tmp = *a;
    *a = *b;
    *b = tmp;

...
int main() {
...
print(M1);
swapMatrix(&M1, &M2);
print(M1);
...

But you need to dereference the pointer, or otherwise you are just swapping around the values of local variables in the swap function. I just explained it here.

Don't worry we all get confused with pointers from time to time.

Tenobaal
  • 637
  • 1
  • 16