Search code examples
carrayspointersfunction-pointersgeneric-programming

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 :).


Solution

  • Adding to a void * is not defined. Cast to char *.

    Possibly need to need to de-reference arr, but I think OP's signature should be adjusted instead. See @user3386109

    Scale the pointer calculation @EOF

    Free the allocated memory too.


    I'd expect passing a void * to be sufficient.

    void SwapInArrayG(void * arr, int a, int b, size_t size) {
        void * temp = malloc(size);
        if (size > 0) {
          assert(temp);
          assert(a >= 0 && b >= 0);
          memcpy(temp, (char *)arr + size*a, size);
          memcpy((char *)arr + size*a, (char *)arr + size*b, size);
          memcpy((char *)arr + size*b, temp, size);
        }
        free(temp);  
    }
    

    Unclear on how OP calls this function, but the following is typical.

    foo_type G[some_size];
    SwapInArrayG(G, index_a, index_b, sizeof *G);
    

    Note: depending on coding goals, using indexes of type size_t is usually preferred over type int.

    Note: that assert(temp); is within if (size > 0) as allocating 0 bytes may return NULL and not be out-of-memory. OTOH, size == 0 is most unusual.