dimanche 31 juillet 2016

C - generic function: swap two items in array

My problem: I would like to create function that can swap any two items in array of generic type.

I have SwapG function that can swap two items of any type:

void SwapG(void * a, void * b, size_t size)
{
    void * temp = malloc(size);
    memcpy(temp, a, size);
    memcpy(a, b, size);
    memcpy(b, temp, size);
}

Here is my attempt of function that would swap two items in array of any type:

void SwapInArrayG(void ** arr, int a, int b, size_t size)
{
    void * temp = malloc(size);
    memcpy(temp, *(arr + a), size);
    memcpy(*(arr + a), *(arr + b), size);
    memcpy(*(arr + b), temp, size);
}

I'm pretty sure I messed the pointers up, still I can't find solution. I would appreciate any help :).

Aucun commentaire:

Enregistrer un commentaire