+ 1
Pointer question
The given code swaps the two integer void swap(int *xp, int *yp) { int temp = *xp; *xp = *yp; *yp = temp; } My question is what happens when we change the above code into following code and can anyone explain me why it is happening? Thanks in advance. void swap(int *xp, int *yp) { int temp = *xp; xp = *yp; // modified line *yp = temp; }
2 ответов
+ 5
In the original one the value pointed by the pointer(integer value) xp will change
At modified one the content of pointer xp (address of int type )will change .
+ 3
The compiler issues an error like this
"invalid conversion from 'int' to 'int*' [-fpermissive]"
Also, a good tip for debugging without a headache is making some queries and see how it will affect both pointers' properties just like so
void swap(int *xp, int *yp)
{
cout << "Before swap: " << *xp << ", " << *yp << endl;
cout << "Address of xp: " << xp << endl;
cout << "Address of yp: " << yp << endl;
cout << "Swapping...\n";
int temp = *xp;
*xp = *yp;
*yp = temp;
cout << "After swap: " << *xp << ", " << *yp << endl;
cout << "Address of xp: " << xp << endl;
cout << "Address of yp: " << yp << endl;
}
Sample output:
Before swap: 5, 10
Address of xp: 0x7aeb559dc8a8
Address of yp: 0x7aeb559dc8ac
Swapping...
After swap: 10, 5
Address of xp: 0x7aeb559dc8a8
Address of yp: 0x7aeb559dc8ac