-2

I need to take a part of an Array, let's say:

32 64 66 69 72 78 81 87 94 95 1 2 4 8 16

realloc a new memory from the end of the array, take the part from 32 to 95 using memcpy to copy it after 16, rearrange the array and return the value of k (k is the size of the first group- 32 to 95, which is 10).
So the output should be:

1 2 4 8 16 32 64 66 69 72 78 81 87 94 95

I've written this code, which doesn't work, Anyone help please :(

int arrangeArray(int** arr, int n)
{
    // your code:
    int i, k = 0, rest = 0;
    for (i = 0; i < n-1;)
    {
        if (arr[i] < arr[++i])
            k++;
    }
    rest = n - k;
    *arr = (int*)realloc(*arr, (n + rest)*sizeof(int));
    memcpy((*arr)+rest, *arr, n*sizeof(int));
    k += rest;
    memcpy(*arr, (*arr) + k, rest * sizeof(int));
    *arr = (int*)realloc(*arr, n * sizeof(int));
    return k;
}
जलजनक
  • 3,072
  • 2
  • 24
  • 30

1 Answers1

1

First, you have a problem with your calculation of k:

  1. Put the increment of i in the for header. It's confusing to do it in the if statement -- at first I thought you had an infinite loop because you weren't incrementing.
  2. Break out of the for loop when the condition fails.
  3. arr[i] should be (*arr)[i].
  4. You need to initialize k = 1 so that the last element in the first group is counted.

Since memcpy() doesn't allow overlapping source and destination, you should double the allocation, rather than just adding enough for k elements. Duplicate the entire array, then copy the portions in the rearranged order back to the beginning.

int arrangeArray(int** arr, int n)
{
    // your code:
    int k = 1, rest;
    for (int i = 0; i < n-1; i++)
    {
        if ((*arr)[i] < (*arr)[i+1]) {
            k++;
        } else {
            break;
        }
    }
    rest = n - k;
    *arr = realloc(*arr, 2 * n * sizeof(int)); // reallocate to double the size
    memcpy((*arr)+n, *arr, n*sizeof(int)); // duplicate the array
    memcpy(*arr, *arr + n + k, rest * sizeof(int)); // copy the rest to the beginning
    memcpy(*arr + rest, *arr + n, k * sizeof(int)); // copy the beginning to the end
    *arr = realloc(*arr, n * sizeof(int)); // reallocate back to the original size
    return k;
}
Barmar
  • 741,623
  • 53
  • 500
  • 612