How to get the unique values of an array in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>

int array_unique(int* arr, int size, int** result, int* result_size) {
    int* temp = (int*)malloc(size * sizeof(int));
     if (temp == NULL) {
        return 0;
    }
    int idx = 0;

    for (int i = 0; i < size; i++) {
        int found = 0;
        for (int j = 0; j < idx; j++) {
            if (arr[i] == temp[j]) {
                found = 1;
                break;
            }
        }
        if (!found) {
            temp[idx++] = arr[i];
        }
    }

    *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 arr[] = {1, 2, 1, 1, 3, 3, 4, 4, 5, 5, 5, 5, 6, 7, 7, 8};
    int* result;
    int result_size;

    int rv = array_unique(arr, sizeof(arr) / sizeof(arr[0]), &result, &result_size);
     if (rv == 0) {
        puts("Error in array_unique()");
        return -1;
    }

    for (int i = 0; i < result_size; i++) {
        printf("%d ", result[i]);
    }
    printf("\n");

    free(result);

    return 0;
}

  
  
/*
run:
  
1 2 3 4 5 6 7 8 
  
*/

 



answered Feb 17, 2025 by avibootz

Related questions

1 answer 142 views
1 answer 122 views
1 answer 77 views
1 answer 87 views
2 answers 137 views
3 answers 131 views
...