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?