Tuesday, November 16, 2010

Adobe Question: Generic Swap in C

void Swap(void* var1, void* var2, int size)
{
    void *temp = malloc(size);
    memcpy(temp,var1,size);
    memcpy(var1, var2, size);
    memcpy(var2, temp, size);

    free (temp);
}

9 comments:

  1. hello sir,
    you forget to free the memory.
    and instead of making system calls ain't it would be better to use stack memory ?

    ReplyDelete
  2. 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)

    ReplyDelete
  3. @Paras

    Yea 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

    ReplyDelete
  4. Second one seems better solution, better abstraction level.

    ReplyDelete
  5. #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;
    }

    }

    ReplyDelete
  6. There's the __typeof macro too in gcc... dont know abt it's portability though...

    ReplyDelete
  7. I don't think that __typeof will work for user defined type

    ReplyDelete