#include<stdio.h>
#include<string.h>
void* swap(void* x, void* y, int size)
{
char* buffer[size];
memcpy(buffer,x,size);
memcpy(x,y,size);
memcpy(y,buffer,size);
}
int main()
{
char* wife = strdup("Wilma Deloitte");
char* husband = strdup("Fred");
printf("\n wife : %s husband : %s \n",wife,husband);
swap(wife,husband,sizeof(char*));
printf("\nAfter swap: \nwife : %s husband : %s \n",wife,husband);
printf("\n sieof : %d \n",(int)sizeof(char*));
return 0;
}
OUTPUT:
wife : Wilma Deloitte husband : Fred
After swap :
wife : Fred husband : Wilma De
sieof : 8
If I pass the &wife and &husband, then the address present inside the husband and wife gets swapped and hence I get the correct output with the fred and wilma deloitte strings swapped .. since the wife and the husband strings are pointing at the address of the fred and wilma deloitte ...
I have passed the address present inside the husband and the wife to be swapped by the memcpy .. I suppose 5 letters (since "fred\0" is 5 char) to be swapped between fred and wilma deloitte .. So the above ouput has to be Fred Deloitte and Wilma.. Why is the output not as expected..