I am trying to write a swap function using pointer(specially a void pointer)by-reference, but my code is not working. Here is my code:
void swap(void *p1,void *p2)
{
int temp;
temp=*((int*)p2);
p2=p1;
p1=&temp;
}
int main()
{
int i=4;
int j=5;
cout<<i<<j<<endl;
swap(&i,&j);
cout<<i<<j<<endl;
return 0;
}
Where am I going wrong?
The code does not work because you are not dereferencing your pointers on assignments. It should be
Note that you are making an assumption that
void*points to anint, which is obviously not always the case. Essentially, you might as well replacevoid*withint*, and get rid of the casts.A more general case of the API should look like this:
Internally, the API should allocate a buffer of size
sz, make amemcpyinto it, and then make a swap, again usingmemcpy.