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.