我正在学习C编程语言并且遇到了qsort()
函数,它允许您对数组的成员进行排序。
根据GNU C库参考手册,qsort()
函数定义如下:
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
我的问题是,由于此函数被定义为使用count
参数的特定数据类型,特别是size_t
,因此发布的大量示例如何使用int
作为size_t
数据类型?在实际代码中使用此函数时,我应该在将参数传递给此函数之前将其显式定义为int
吗?
GNU C库参考手册中使用的示例也使用#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;
}
作为参数,一切都按预期工作:
count
但是,我认为此示例中的size_t count = sizeof (muppets) / sizeof (struct critter);
应定义为:
<PropertyGroup Label="Globals">
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
</PropertyGroup>
我是否在思考这个问题,我们将不胜感激。谢谢。