How to remove all duplicates from a array that was created with dynamic allocation?

Viewed 92

I wrote a program that dynamically allocates for a new array that contains elements from two other arrays. However the program dose not completely remove all duplicates from the new array. Instead of outputting 1 2 3 4 5, instead it outputs 1 2 3 3. I tried to fix the problem by first sorting the array, however that did not help at all.

int koko(int va, int vb, int *kar, int *a, int *b) {
    int *c;
    int kar2 = (*kar);
    c = (int)malloc(kar2 * sizeof(int));
    int i, j, u, temp;

    //takes all elements from the first array
    for (i = 0; i < va; i++) {
        c[i] = a[i];
    }

    //takes all elements from the second array
    for (i = 0, j = va; j < kar2 && i < vb; i++, j++) {
        c[j] = b[i];
    }

    //sorts the array
    for (i = 0; i < kar2; i++) {
        for (j = i + 1; j < kar2; j++) {
            if (c[i] > c[j]) {
                temp = c[i];
                c[i] = c[j];
                c[j] = temp;
            }
        }
    }

    //removes all duplicates(or it should at least)
    for (i = 0; i < kar2; i++) {
        for (j = i; j < kar2; j++) {
            if (c[j] == c[i]) {
                for (u = j; u < kar2; u++) {
                    c[u] = c[u + 1];
                }

                kar2--;
            }
            else {
                j++;
            }
        }
    }

    c = (int)realloc(c, sizeof(int) * kar2);
    (*kar) = kar2;
    return c;
}

int main() {
    int *s;
    int a[] = {1, 2, 3, 3, 3, 3, 5};
    int b[] = {1, 2, 2, 2, 3, 4};
    int va = sizeof(a) / sizeof a[0];
    int vb = sizeof(b) / sizeof b[0];
    int kar = va + vb;
    s = koko(va, vb, &kar, a, b);

    for (int q = 0; q < kar - 1; q++) {
        printf("%d\t", s[q]);
    }

    free(s);
}

This my code that I wrote. Dose anyone by any chance see where the problem is?

1 Answers
    // there were a few off-by-1 errors:
    // loops were accessing 1 element beyond the array (fixed with kar2 - 1)
    // after moving array elements, the current element wasn't being
    // re-tested with its new neighbor (fixed with i--)

    // remove duplicates
    for (i = 0; i < (kar2 - 1); i++) {
        // different, move onto the next pair
        if (c[i] != c[i + 1])
            continue;

        // duplicate, move array elements back by 1
        for (j = i + 1; j < (kar2 - 1); j++)
            c[j] = c[j + 1];

        // account for duplicate
        kar2--;

        // after the second loop, new next element could be another duplicate;
        // need to re-test the current element with the new next element
        i--;
    }
Related