Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <ol> <li><code>qsort</code> was made this way so it could be used as a generic sorter. If it would use <code>int</code> from the start it could only be used to compare integers. This way you could also, for example, sort strings by passing <code>strcmp</code> as the compare function to <code>qsort</code>.</li> <li><code>*(int*)a</code> casts <code>a</code> to a pointer-to-<code>int</code> and then dereferences it, so you get the integer stored at <code>a</code>. Note that this doesn't change <code>a</code> or the value that <code>a</code> points to.</li> <li><p><a href="http://linux.die.net/man/3/qsort" rel="nofollow"><code>qsort</code></a> requires 4 arguments: the array to sort, the number of elements in that array and the size of the elements and finally the compare function. It needs all this information, because again, it is made to be as generic as possible. </p> <p>It needs the number of elements because in C pointers don't carry information about the size of the buffer that follows them. And it needs to know the size of each element so it can pass the elements to the compare function correctly. For examle, to compare <code>int</code>s you would pass <code>sizeof(int)</code> as the size parameter. To compare strings you would use <code>sizeof(char *)</code>.</p></li> </ol> <p><strong>ADDIT</strong> as suggested by H2CO3 the reason for using <code>const void *</code> is to indicate that the compare function may not change the value pointed to by <code>a</code> and <code>b</code>. This, of course, to ensure that sorting the array doesn't suddenly change the values in the array. And, as H2CO3 said, it would be cleaner to cast to <code>(const int *)</code> so that you cannot accidentally change the value after casting it:</p> <pre><code>return *(const int *)a - *(const int *)b; </code></pre> <p>You could also get rid of the cast with:</p> <pre><code>int compare(const void * a, const void * b){ const int * ia = a; const int * ib = b; return *ia - *ib; } </code></pre> <p>depending on your tastes regarding casts. (I prefer to avoid them)</p> <p>Finally, to clarify the asterisks:</p> <pre><code>*(int *)a ^ ^ | └ cast to integer pointer └ dereference (integer) pointer </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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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