title: sort array in C, return sorted indices
body: <p>I'm using an example from <a href="https://phoxis.org/2012/07/12/get-sorted-index-orderting-of-an-array/" rel="nofollow noreferrer">https://phoxis.org/2012/07/12/get-sorted-index-orderting-of-an-array/</a> where he returns the sort indices from a sort of an array, i.e.</p>
  
  <p><code>3,4,2,6,8</code> returns <code>4,3,1,0,2</code> (+1 for each index in R).  This is the equivalent of R's <code>order</code> function</p>
  
  <p>I've translated his/her code to work as a function returning an array of sorted indices.  The code gives the correct answer.</p>
  
  <p><a href="https://stackoverflow.com/questions/24586499/keeping-track-of-the-original-indices-of-an-array-after-sorting-in-c">keeping track of the original indices of an array after sorting in C</a> has a similar response, but as @BLUEPIXY warns, his solution doesn't work in all circumstances.  I need something that will work in all circumstances, including ties.</p>
  
  <p>however, the original author uses a global pointer, which causes a memory leak, and <code>free()</code> doesn't fix it.  which I don't know how to do this without the global pointer.</p>
  
  <p>How can I fix this memory leak, or at least return sorted indices in C that will always work?</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  /* holds the address of the array of which the sorted index
   * order needs to be found
   */
  int * base_arr = NULL;
  /* Note how the compare function compares the values of the
   * array to be sorted. The passed value to this function
   * by `qsort' are actually the `idx' array elements.
   */
  static int compar_increase (const void * a, const void * b) {
      int aa = *((int * ) a), bb = *((int *) b);
      if (base_arr[aa] &lt; base_arr[bb]) {
          return 1;
      } else if (base_arr[aa] == base_arr[bb]) {
          return 0;
      } else {
  //  if (base_arr[aa] &gt; base_arr[bb])
          return -1;
       }
  }
  
  int * order_int (const int * ARRAY, const size_t SIZE) {
      int * idx = malloc(SIZE * sizeof(int));
      base_arr = malloc(sizeof(int) * SIZE);
      for (size_t i = 0; i &lt; SIZE; i++) {
          base_arr[i] = ARRAY[i];
          idx[i] = i;
      }
      qsort(idx, SIZE, sizeof(int), compar_increase);
      free(base_arr); base_arr = NULL;
      return idx;
  }
  
  
  int main () {
      const int a[] = {3,4,2,6,8};
      int * b = malloc(sizeof(int) * sizeof(a) / sizeof (*a));
      b = order_int(a, sizeof(a) / sizeof(*a));
      for (size_t i = 0; i &lt; sizeof(a)/sizeof(*a); i++) {
          printf("b[%lu] = %d\n", i, b[i]+1);
      }
      free(b); b = NULL;
      return 0;
  }
  </code></pre>