Firzen
Firzen

Reputation: 2095

Swap items of void* pointer array without memcpy in C

I am writing some school project, and I need to swap two items of void* pointer array. I can do this with something like following code:

void swap(void *base, int len, int width)
{
    void *p = malloc(width);

    memcpy(p,base,width);
    memcpy(base,(char*)base+width,width);
    memcpy((char*)base+width,p,width);

    free(p);
}

But I need to swap items WITHOUT memcpy, only with malloc, realloc and free. Is that even possible?

Thank you

Upvotes: 2

Views: 2899

Answers (2)

ProphetV
ProphetV

Reputation: 103

The array contents can be swapped in place, using only a char as a temporary variable.

void swap(void *base, int len, int width)
{
  int i;
  char t;

  for (i = 0; i < width; i++)
  {
    t = base[i];
    base[i] = base[i + width];
    base[i + width] = t;
  }
}

Upvotes: -1

David Ranieri
David Ranieri

Reputation: 41017

Why don't swap in this way?:

void swap(void *v[], int i, int j)
{
    void *temp;

    temp = v[i];
    v[i] = v[j];
    v[j] = temp;
}

As qsort does (swaps elements within the array):

void sort(void *v[], int left, int right, int (*comp)(const void *, const void *))
{
    int i, last;

    if (left >= right) return;
    swap(v, left, (left + right) / 2);
    last = left;
    for (i = left + 1; i <= right; i++) {
        if ((*comp)(v[i], v[left]) < 0)
            swap(v, ++last, i);
    }
    swap(v, left, last);
    sort(v, left, last - 1, comp);
    sort(v, last + 1, right, comp);
}

Upvotes: 2

Related Questions