- 論壇徽章:
- 0
|
我在網(wǎng)上找了一下,這段代碼可能出現(xiàn)在以下代碼中
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#define MAXLINES 1024
static int scomp(const void *, const void *);
main(int argc, char *argv[])
{
int i, n;
char *strings[MAXLINES], buf[BUFSIZ];
if (argc > 1)
assert(freopen(argv[1],"r",stdin));
/* Read lines into dynamic memory */
for (n = 0; n < MAXLINES && fgets(buf,BUFSIZ,stdin); ++n)
{
strings[n]: malloc(strlen(buf)+1);
assert(strings[n]);
strcpy(strings[n],buf);
}
qsort(strings, n, sizeof strings[0], scomp);
/* Free memory */
for (i = 0; i < n; ++i)
{
fputs(strings,stdout);
free(strings);
}
return 0;
}
static int scomp(const void *p1, const void *p2)
{
char *a = * (char **) p1;
char *b = * (char **) p2;
return strcmp(a,b);
}
上面這段代碼用于排列不規(guī)則長度的字符串,摘自http://www.freshsources.com/19940197.HTM。
那么我再看了一下qsort函數(shù)的原型
void qsort(void *base,size_t nelem,size_t width,int (*Comp)(const void *,const void *));其中:
*base 為要排序的數(shù)組
nelem 為要排序的數(shù)組的長度
width 為數(shù)組元素的大。ㄒ蛔纸Y為單位)
(* Comp)(const void *p1,const void *p2) 為判斷大小函數(shù)的指針,這個函數(shù)需要自己定義,如果p1>p2,函數(shù)返回-1;a<b,函數(shù)返回1;a==b函數(shù)返回0。
那么scomp的用意就是對不同的類型中的字符串進行比較。如可能不是char,而是某個struct 中的char str[],所以void更有可讀性和通用性。
這個函數(shù)就是p1指向a,p2指向b
http://www.freshsources.com/199401A1.HTM
[ 本帖最后由 waternie 于 2008-8-18 22:36 編輯 ] |
|