I wrote this intending it to be either able to swap a structure, or just the data defined within a structure.
Will the swap function be able to do this, because.. when i tested it, it seemed to fail. but i didnt except it too.
It fails because all it does is swap the pointers within the swap() function itself because the pointers are passed by value, not by reference.
void swap(void** a, void** b)
{
void* temp = *a;
*a = *b;
*b = temp;
}
Now the above will work ONLY if you pass a pointer to a pointer. It will also fail if you pass a pointer to some object.
int main()
{
int a = 1;
int b = 2;
swap(&a, &b); // <<<<<<< wrong
int* c = &a;
int* d = &b;
swap(&c, &d); // <<< OK
// when the swap returns, pointer c will point to b and pointer d will point to a.
// The value of a and b are still the same, only the two pointers
// were swapped
it should atleast work for swapping the data stored within the structure though, shouldnt it?
No.
Last edited by Ancient Dragon; May 17th, 2008 at 9:48 am.
Sponsor
Team Colleague
Featured Poster
Reputation Points: 5608
Solved Threads: 2282
Retired and Enjoying Life
Offline 21,951 posts
since Aug 2005