How to get unique values from two arrays in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
  
int get_unique_values(const int* arr1, int size1, const int* arr2, int size2, int** result, int* result_size) {
    int* temp = (int*)malloc((size1 + size2) * sizeof(int));
    if (temp == NULL) {
        return 0;
    }
    int idx = 0;
  
    for (int i = 0; i < size1; i++) {
        int found = 0;
        for (int j = 0; j < size2; j++) {
            if (arr1[i] == arr2[j]) {
                found = 1;
                break;
            }
        }
        if (!found) {
            temp[idx++] = arr1[i];
        }
    }
  
    for (int j = 0; j < size2; j++) {
        int found = 0;
        for (int i = 0; i < size1; i++) {
            if (arr2[j] == arr1[i]) {
                found = 1;
                break;
            }
        }
        if (!found) {
            temp[idx++] = arr2[j];
        }
    }
  
    *result = (int*)malloc(idx * sizeof(int));
    if (result == NULL) {
        free(temp);
        return 0;
    }
    for (int i = 0; i < idx; i++) {
        (*result)[i] = temp[i];
    }
    *result_size = idx;
  
    free(temp);
    
    return 1;
}
  
int main() {
    int arr1[] = {1, 3, 6, 8, 12, 90};
    int arr2[] = {2, 3, 5, 6, 7, 8, 96};
    int size1 = sizeof(arr1) / sizeof(arr1[0]);
    int size2 = sizeof(arr2) / sizeof(arr2[0]);
    int* result;
    int result_size;
  
    int rv = get_unique_values(arr1, size1, arr2, size2, &result, &result_size);
    
    if (rv == 0) {
        puts("Error in get_unique_values()");
        return -1;
    }
  
    for (int i = 0; i < result_size; i++) {
        printf("%d ", result[i]);
    }
  
    free(result);
  
    return 0;
}
  
   
   
/*
run:
   
1 12 90 2 5 7 96 
   
*/

 



answered Feb 16, 2025 by avibootz
edited Feb 17, 2025 by avibootz

Related questions

1 answer 84 views
1 answer 116 views
1 answer 103 views
1 answer 98 views
1 answer 201 views
1 answer 83 views
1 answer 106 views
...