and I tried to use it to swap two pointers in the main funtion and it doesnt work:
1 2 3 4 5 6 7 8
int main(){
int a,b;
int *pointer1, *pointer2;
scanf("%d,%d",&a,&b);
pointer1=&a; pointer2=&b;
swap(pointer1, pointer2);
printf("\n%d,%d,\n",*pointer1,*pointer2);
}
Ater the execution, the two pointers are still pointing to the original memory location(pointer1=&a; pointer2=&b;), while I expect them to point to the swapped location(pointer1=&b; pointer2=&a;).
My textbook doesn't explain this very well,
Can anybody help?
You never call the swap function, but it doesn't work anyway.The pointers inside the swap function are copies of the pointers that you pass to the function so the original pointers will not be affected. If you instead pass the pointers by reference it will modify the original pointers.
Oh sorry I did call the function in my original code but I made mistake when writing this thread haha. Have edited it.
And in the code you provided, are you swapping the pointer's content by using another set of pointers that points to the location of pointer1 and pointer2?
And in the code you provided, are you swapping the pointer's content by using another set of pointers that points to the location of pointer1 and pointer2?
If I may (as Peter87 appears to have departed for now).
No. That would be this solution:
1 2 3 4 5 6 7
// passing addresses of pointers by value (pointers to pointers)
void swap(int** pp1, int** pp2) {
int *p;
p = *pp1;
*pp1 = *pp2;// changing which address is pointed to.
*pp2 = p;
}
Peter87 passed two pointers by reference. This is so the 'values' of the pointers (the addresses pointed to) may be changed within the function. This is for the same reason that we pass any variable type to a function by reference.
He is doing the equivalent of:
1 2 3 4 5 6 7
void swapValues( int& x1, int& x2 )
{
int x;
x = x1;
x1 = x2;
x2 = x;
}