I want to swap a pointer wich points to another pointer which points to an array. I can do it if the pointer points to a variable but not to an array.
#include <iostream>
int swap(int **val1, int **val2){
int tmp=0;
tmp=**val1;
**val1=**val2;
**val2=tmp;
};
int main() {
int a=5;
int b=3;
//int a[5]={1,2,3,4,5 };
//int b[5]={22,34,56,78,89};
int *p1=0;
int *p2=0;
p1=&a;
p2=&b;
vertausche(&p1, &p2);
printf("%d\n",a);
printf("%d",b);
return 0;
}
When I try my swap function from above for an array only the first elements in the array swaps. Which is kind of logical because the Pointer **pp1 shows only to the first element but I don't know how I can swap the other elements.
I tried to do it in a for loop like this:
Thanks for the answer. Is it possible to swap only the addresses from the pointers so the function header would look like void swap (int **a, int **b) so that I only swap the pointer ?
#include <iostream>
void vertausche(int*& a, int*& b) {
int *tmp = a;
a = b;
b = tmp;
}
void print(constint *a, int size) {
for (int i = 0; i < size; ++i)
std::cout << a[i] << ' ';
std::cout << '\n';
}
int main() {
int a[5] = {1,2,3,4,5};
int b[5] = {22,34,56,78,89};
int *pa = a, *pb = b;
vertausche(pa, pb);
print(pa, 5);
print(pb, 5);
}