Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You can implement the first as a macro:</p> <pre><code>#define incr(x) (++(x)) </code></pre> <p>Of course, this can have unpleasant side effects if you're not careful. It's about the only method C provides for applying the same operation to any of a variety of types though. In particular, since the macro is implemented using text substitution, by the time the compiler sees it, you just have the literal code <code>++whatever;</code>, and it can apply <code>++</code> properly for the type of item you've provided. With a pointer to void, you don't know much (if anything) about the actual type, so you can't do much direct manipulation on that data).</p> <p><code>void *</code> is normally used when the function in question doesn't really need to know the exact type of the data involved. In some cases (e.g., <code>qsort</code>) it uses a callback function to avoid having to know any details of the data.</p> <p>Since it does both sort and swap, let's look at qsort in a little more detail. Its signature is:</p> <pre><code>void qsort(void *base, size_t nmemb, size_t size, int(*cmp)(void const *, void const *)); </code></pre> <p>So, the first is the <code>void *</code> you asked about -- a pointer to the data to be sorted. The second tells qsort the number of elements in the array. The third, the size of each element in the array. The last is a pointer to a function that can compare individual items, so <code>qsort</code> doesn't need to know how to do that. For example, somewhere inside qsort will be some code something like:</p> <pre><code>// if (base[j] &lt; base[i]) ... if (cmp((char *)base+i, (char *)base+j) == -1) </code></pre> <p>Likewise, to swap two items, it'll normally have a local array for temporary storage. It'll then copy bytes from <code>array[i]</code> to its temp, then from <code>array[j]</code> to <code>array[i]</code> and finally from <code>temp</code> to <code>array[j]</code>:</p> <pre><code>char temp[size]; memcpy(temp, (char *)base+i, size); // temp = base[i] memcpy((char *)base+i, (char *)base+j, size); // base[i] = base[j] memcpy((char *)base+j, temp, size); // base[j] = temp </code></pre>
 

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