I am learning the C programming language and have come across the qsort()
function that lets you sort members of an array.
According to the GNU C library reference manual, the qsort()
function is defined as follows:
void qsort (void *array, size_t count, size_t size, comparison_fn_t compare)
http://www.gnu.org/software/libc/manual/html_node/Array-Sort-Function.html#Array-Sort-Function
My question is, since this function is defined as using a certain data type for the count
parameter, specifically size_t
, how come a lot of examples that are posted use int
as the datatype? When using this function in actual code, should I explicitly define my arguments as being size_t
before passing them into this function?
The example that is used in the GNU C library reference manual also uses an int
as an argument and everything works as expected:
#include <stdio.h>
#include <stdlib.h>
struct critter
{
const char *name;
const char *species;
};
struct critter muppets[] =
{
{"Kermit", "frog"},
{"Piggy", "pig"},
{"Gonzo", "whatever"},
{"Fozzie", "bear"},
{"Sam", "eagle"},
{"Robin", "frog"},
{"Animal", "animal"},
{"Camilla", "chicken"},
{"Sweetums", "monster"},
{"Dr. Strangepork", "pig"},
{"Link Hogthrob", "pig"},
{"Zoot", "human"},
{"Dr. Bunsen Honeydew", "human"},
{"Beaker", "human"},
{"Swedish Chef", "human"}
};
int count = sizeof (muppets) / sizeof (struct critter);
int critter_cmp (const void *v1, const void *v2)
{
const struct critter *c1 = v1;
const struct critter *c2 = v2;
return strcmp (c1->name, c2->name);
}
int main()
{
qsort (muppets, count, sizeof (struct critter), critter_cmp);
return 0;
}
However, I feel that count
in this example should be defined as:
size_t count = sizeof (muppets) / sizeof (struct critter);
Am I overthinking this, any help would be appreciated. Thank you.