1. 程式人生 > >一天一個庫函式-for C

一天一個庫函式-for C

1.對連續記憶體下的資料進行快速排序

<stdlib.h> 
void qsort(void *buf, size_t num, size_t size, int (*compare)(const void* ,const void*);

作用:對buf 指向的資料(包含num 項,每項的大小為size)進行快速排序。如果函式compare 的第一個引數小於第二個引數,返回負值;如果等於返回零值;如果大於返回正值。函式對buf 指向的資料按升序排序。

int compareUp(const void* x, const void* y)
{
    int* a=(int*)x; int* b=(int*)y;
    return (*a<*b)?-1:( (*a==*b)?0:1 ); 
}//預設升序
int compareDown(const void* x, const void* y)
{
    return -compareUp(x,y);
}//降序

2. 字串複製

    #include <string.h>
    char* strncpy(char* to, char* from, size_t count);

作用:將字串from 中至多count個字元複製到字串to中。如果字串from 的長度小於count,其餘部分用’\0’填補。注意:如果字串from的長度大於count,則只複製相應的字元,並不保證在結尾新增’\0’字元,最後返回處理完成的字串。