Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You could utilise <code>qsort</code> from <code>stdlib.h</code> to ensure your array is sorted into ascending order to remove the need for a nested loop.</p> <p>Note that qsort requires a pointer to a function (int_cmp in this instance), i've included it below.</p> <p>This function, <code>int_array_unique</code> returns the duplicate free array 'in-place' i.e. it overwrites the original and returns the length of the duplicate free array via the <code>pn</code> pointer</p> <pre><code>/** * Return unique version of int array (duplicates removed) */ int int_array_unique(int *array, size_t *pn) { size_t n = *pn; /* return err code 1 if a zero length array is passed in */ if (n == 0) return 1; int i; /* count the no. of unique array values */ int c=0; /* sort input array so any duplicate values will be positioned next to each * other */ qsort(array, n, sizeof(int), int_cmp); /* size of the unique array is unknown at this point, but the output array * can be no larger than the input array. Note, the correct length of the * data is returned via pn */ int *tmp_array = calloc(n, sizeof(int)); tmp_array[c] = array[0]; c++; for (i=1; i&lt;n; i++) { /* true if consecutive values are not equal */ if ( array[i] != array[i-1]) { tmp_array[c] = array[i]; c++; } } memmove(array, tmp_array, n*sizeof(int)); free(tmp_array); /* set return parameter to length of data (e.g. no. of valid integers not * actual allocated array length) of the uniqe array */ *pn = c; return 0; } /* qsort int comparison function */ int int_cmp(const void *a, const void *b) { const int *ia = (const int *)a; // casting pointer types const int *ib = (const int *)b; /* integer comparison: returns negative if b &gt; a and positive if a &gt; b */ return *ia - *ib; } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload