C - fastest method to swap two memory blocks of equal size?

前端 未结 9 2596
春和景丽
春和景丽 2021-02-20 05:20

What is the fastest way to swap two non-overlapping memory areas of equal size? Say, I need to swap (t_Some *a) with (t_Some *b). Considering space-tim

9条回答
  •  名媛妹妹
    2021-02-20 06:09

    #include 
    #include 
    
    static void swap_elements_of_array(void* base, size_t size_of_element, int a, int b);
    static void swap_elements_of_array(void* base, size_t size_of_element, int a, int b)
    {
    union {
        int i; /* force alignment */
        char zzz[size_of_element] ; /* VLA */
        } swap;
    memcpy (swap.zzz, (char*)base + a * size_of_element,size_of_element);
    memcpy ((char*)base + a * size_of_element,(char*)base + b * size_of_element,size_of_element);
    memcpy ((char*)base + b * size_of_element, swap.zzz, size_of_element);
    }
    
    int main (void)
    {
    unsigned idx,array[] = {0,1,2,3,4,5,6,7,8,9};
    
    swap_elements_of_array(array, sizeof array[0], 2, 5);
    
    for (idx=0; idx < 10; idx++) {
        printf( "%u%c", array[idx], (idx==9) ? '\n' : ' ' );
        }
    return 0;
    }
    

    The intention of the above fragment is to allow the highly optimised libc versions of memcpy (or inlining by the compiler) to take all the freedom they need. The alignment is crucial. If VLAs are not avalable (before C99) a macro can be composed, using a funky do-while.

提交回复
热议问题