I was asked to create a new array without duplicate integars from an array.
I think I made a mistake in my code but can't notice anything wrong.
The output for "1, 2, 1, 2, 1, 4" is "1, 2, 2, 4".
It's supposed to be "1, 2, 4"
Would like to learn about my mistake.
// Exercise 2 -
void Ex2() {
int i, counter = 1, size = -1;
int* array = input_dynamic_array(&size);
int* newArr = (int*)malloc((size)* sizeof(int));
newArr[0] = array[0];
assert(array);
for (i = 1; i < size; i++) {
if (!find_num_in_newArr(newArr, size, array[i])) {
newArr[counter++] = array[i];
}
}
newArr = (int*)realloc(newArr, (counter)*sizeof(int));
printArray(newArr, counter);
free(array);
free(newArr);
}
bool find_num_in_newArr(int *newArr, int size, int num) {
int i;
for (i = 0; i < size; i++) {
if (newArr[i] == num) {
return true;
}
return false;
}
}
int* input_dynamic_array(int *size)
{
int *array;
int ii;
printf("Enter array size: ");
scanf("%d", size);
array = (int*)malloc((*size) * sizeof(int));
assert(array);
printf("Enter %d integer numbers: ", *size);
for (ii = 0; ii < *size; ii++)
scanf("%d", array + ii);
return array;
}