Hello, so I am trying to write a program that creates an array with random numbers and then making a new array with the same values but with no duplicates. When I run the program, the results are not what they should come out being and I'm not too sure why this his happening! If anyone could shed some light on my brain it would be greatly appreciated!
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void binarySearch(int rand_nums[], int size);
void printArray(int nums[], int size);
int main(int argc, const char * argv[])
{
srand((unsigned)time(NULL));
int rand_nums[20];
int rand_num_size = sizeof(rand_nums)/sizeof(rand_nums[0]);
// fills array with random nums 0-10
for(int i = 0; i < rand_num_size; i++)
rand_nums[i] = rand() % 10;
binarySearch(rand_nums, rand_num_size);
return 0;
}
void printArray(int nums[], int size) {
printf("Array set: ");
for(int i = 0; i < size; i++)
printf("%d ", nums[i]);
}
void binarySearch(int rand_nums[], int size) {
int counter = 0;
// goes through array and makes duplicates NULL
for(int i = 0; i < size; i++) {
for(int j = i + 1; j < size; j++) {
if(rand_nums[i] == rand_nums[j] && rand_nums[j] != (int)NULL && rand_nums[i] != (int)NULL) {
rand_nums[j] = (int)NULL;
counter++;
}
}
}
// new array with custome size
int new_array[size-counter];
size_t new_array_size = sizeof(new_array)/sizeof(new_array[0]);
int index = 0;
// fills new array with non NULL values of rand_nums
for(int g = 0; g < new_array_size; g++) {
if(rand_nums[g] != (int)NULL) {
new_array[index] = rand_nums[g];
index++;
}
}
// victory
printf("OLD Array:\n");
printArray(rand_nums, size);
printf("\n\nNEW Array:\n");
printArray(new_array, new_array_size);
}