hello sir, you forget to free the memory.and instead of making system calls ain't it would be better to use stack memory ?
Another solution can be using macro. It will take only two parameter just like original Swap -#define SWAP(a, b) void* temp = malloc(sizeof(a)); \memcpy(temp, &a, sizeof(a)); \memcpy(&a, &b, sizeof(a)); \memcpy(&b, temp, sizeof(a)); \free (temp)
@ParasYea agree.. but this code is just for hint how it can be achieved. Any ways thanks for pointing out the mistakes. Well if you have better solution, then Welcome.I am correcting my solution
Second one seems better solution, better abstraction level.
Thanks Sir, for verification
#define swap(arg1,arg2) Swap(&arg1,&arg2,sizeof(arg1));void Swap(void*,void*,int);int main(int argc,char* argv[]) {double a = 10.10, b = 10.7;swap(a,b);printf(" %f %f " , a,b);}void Swap(void * arg1, void * arg2, int size){int i;char * a=arg1, *b=arg2, temp;for( i=0;i<size;i++,a++,b++){temp = *a;*a=*b;*b=temp;}}
Thanks Paras :)
There's the __typeof macro too in gcc... dont know abt it's portability though...
I don't think that __typeof will work for user defined type
hello sir,
ReplyDeleteyou forget to free the memory.
and instead of making system calls ain't it would be better to use stack memory ?
Another solution can be using macro. It will take only two parameter just like original Swap -
ReplyDelete#define SWAP(a, b) void* temp = malloc(sizeof(a)); \
memcpy(temp, &a, sizeof(a)); \
memcpy(&a, &b, sizeof(a)); \
memcpy(&b, temp, sizeof(a)); \
free (temp)
@Paras
ReplyDeleteYea agree.. but this code is just for hint how it can be achieved. Any ways thanks for pointing out the mistakes. Well if you have better solution, then Welcome.
I am correcting my solution
Second one seems better solution, better abstraction level.
ReplyDeleteThanks Sir, for verification
ReplyDelete#define swap(arg1,arg2) Swap(&arg1,&arg2,sizeof(arg1));
ReplyDeletevoid Swap(void*,void*,int);
int main(int argc,char* argv[])
{
double a = 10.10, b = 10.7;
swap(a,b);
printf(" %f %f " , a,b);
}
void Swap(void * arg1, void * arg2, int size){
int i;
char * a=arg1, *b=arg2, temp;
for( i=0;i<size;i++,a++,b++){
temp = *a;
*a=*b;
*b=temp;
}
}
Thanks Paras :)
ReplyDeleteThere's the __typeof macro too in gcc... dont know abt it's portability though...
ReplyDeleteI don't think that __typeof will work for user defined type
ReplyDelete