• + 0 comments

    C w/ memory copy

    int* rotateLeft(int d, int arr_count, int* arr, int* result_count) {
        assert(result_count);
        *result_count = arr_count;
        
        //
        // Use extra memory to rotate an array
        // 1. copy into extra memory [0]..[d]
        // 2. then copy the rest of the array [d]..[end] into the [0] index
        // 3. then copy the extra memory bytes into rest of the main array
        //     starting from [d]
        //
        
        if (!arr_count || arr_count == 1 || !arr) return arr;
    
        int* extra = malloc(sizeof(int) * d);
        assert(extra);
    
        memcpy(extra, arr, d * sizeof(int));
        memcpy(arr, arr + d, sizeof(int) * (arr_count - d));
        memcpy(arr + arr_count - d, extra, d * sizeof(int));
        
        free(extra);
        return arr;
    }