C中的交织数组

时间:2018-10-06 01:11:36

标签: c arrays interleave

我以前发布过,但是我没有正确格式化或添加我的代码。假设我有一个整数数组x = [1,2,3]。给定一个值i,我想创建一个数组x ^ i,如果i = 3,则数组x ^ i = [1,1,1,2,2,2,3,3,3]。如果i = 5,数组x ^ i = [1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,3,4,4,4,4,4,4 ,5,5,5,5,5]。我正在为此动态分配内存。

但是,我对i = 3的代码正在创建一个数组= [1,2,3,1,2,3,1,2,3]。我尝试了许多不同的方法,得到了类似[1,1,1,1,1,1,1,1,1]或[3,3,3,3,3,3,3,3, 3],但永远不会是正确答案。

这是我的代码:

void binary_search(int size_a, int * A, int size_x, int *X, int max_i, int min_i){

    int i, j, k, count = 0, max_repeat = 0;

    while(min_i <= max_i){

    int repeats = (max_i + min_i)/2;

    int * temp = realloc(X, size_x * sizeof(int) * repeats);
    X = temp;


    for(k = 0; k < size_x; ++k){
    int idx = size_x - k -1;
    temp = &X[idx];
        for(j = 0; j < repeats; ++j){
            X[idx * repeats + j] = *temp;
        }
    }

    printf("New X: ");
        for(i = 0; i < size_x * repeats; i++){
            printf("%d ", X[i]);
        }

    int count = 0;
    for(i = 0; i < size_x * repeats; i++){
        for(j = 0; j < size_a; j++){
            if(A[j] == X[i]){
                count++;
                i++;
            }
        }
    }

    if (count == size_x * repeats){
        printf("Low: %d Mid %d High % d Passes\n", min_i, repeats, max_i);
        min_i = repeats + 1;
    }
    else
        printf("Low: %d Mid %d High % d Fails\n", min_i, repeats, max_i);
        max_i = repeats - 1;
    }

}

变量重复表示x ^ i中的值i。

输出是这样的:

Old X: 1 2 3 

New X: 1 1 1 2 2 2 3 3 3 Low: 0 Mid 3 High  6 Fails

New X: 1 1 1 Low: 0 Mid 1 High  2 Fails

New X: Low: 0 Mid 0 High  0 Fails

第一次迭代是正确的,但是第二次迭代不应为[1,1,1],而应为[1,2,3]。

我要去哪里错了?

1 个答案:

答案 0 :(得分:0)

您在这里:

int misleading_function_names_is_bad_practice(size_t xsize, int x[xsize], size_t i)
{
    void * const tmp = realloc(x, xsize * sizeof(*x) * i);
    if (tmp == NULL) {
       return -__LINE__;
    }
     x = tmp;

     for (size_t k = 0; k < xsize; ++k) {
         // index of the last original digit counting down
         const size_t idx = xsize - k - 1;
         const int tmp = x[idx];
         for (size_t l = 0; l < i; ++l) {
              // fill from the back
              x[idx * i + l] = tmp;
         }
      }

      return 0;
}

可通过onlinegdb获得实时示例。