Search code examples
cswapmemcpyvoid-pointersincomplete-type

Swapping values of undefined size with memcpy


I am trying to swap the value of two elements in an array, where i know their size as a variable, my code looks like that:

void function(void *array, size_t size) {
    /*in this example the array's members are 2
    and i want to swap them*/
    void *help = malloc(size);

    memcpy(help, &array[0], size);
    memcpy(&array[0], &array[1], size);
    memcpy(&array[1], help, size);
    free(help);
}

Am i missing something?


Solution

  • The type void is incomplete type. So you may not dereference a pointer of the type void *.

    Write the function like

    void function(void *array, size_t size) {
        /*in this example the array's members are 2
        and i want to swap them*/
        void *help = malloc(size);
    
        memcpy(help, array, size);
        memcpy( array, ( char * )array + size, size);
        memcpy( ( char * )array + size, help, size);
        free(help);
    }
    

    Here is a demonstrative program.

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    void function(void *array, size_t size) {
        /*in this example the array's members are 2
        and i want to swap them*/
        void *help = malloc(size);
    
        memcpy(help, array, size);
        memcpy( array, ( char * )array + size, size);
        memcpy( ( char * )array + size, help, size);
        free(help);
    }
    
    int main(void) 
    {
        int a[] = { 1, 2 };
        const size_t N = sizeof( a ) / sizeof( *a );
    
        for ( size_t i = 0; i < N; i++ ) printf( "%d ", a[i] );
        putchar( '\n' );
    
        function( a, sizeof( int ) );
    
        for ( size_t i = 0; i < N; i++ ) printf( "%d ", a[i] );
        putchar( '\n' );
    
        return 0;
    }
    

    Its output is

    1 2 
    2 1