C Primer Plus(第六版)16.18 编程练习 第6题

/* qsorter.c -- using qsort to sort groups of numbers */
#include
#include
#include
#include

#define NUM 5
#define LEN 10

struct names
{
    char first[LEN];
    char last[LEN];
};
const unsigned char allChar[63] = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";

void generateString(char * dest,int len);
void fillnames(struct names staff[], int n);
void shownames(struct names staff[], int n);
int mycomp(const void * p1, const void * p2);

int main(void)
{
    struct names staff[NUM];
    srand((unsigned int) time(NULL));
    fillnames(staff, NUM);
    puts("Random list:");
    shownames(staff, NUM);
    qsort(staff,NUM,sizeof (struct names) ,mycomp) ;
    puts("\nSorted list:");
    shownames(staff, NUM);
    return 0;
}

void fillnames(struct names staff[], int n)
{
    int index;
    
    for( index = 0; index < n; index++)
    {
        generateString(staff[index].first, LEN);
        generateString(staff[index].last, LEN);
    }
}

void shownames(struct names staff[], int n)
{
    int index;
    
    for( index = 0; index < n; index++)
    {
        printf("第%d个\n", index);
        printf("last:%s", staff[index].last);
        printf("first:%s\n", staff[index].first);
    }
}

/* sort by increasing value */
int mycomp(const void * p1, const void * p2)
{
    /* need to use pointers to double to access values   */
    const struct names * ps1 = (const struct names *) p1;
    const struct names * ps2 = (const struct names *) p2;
    int res;
    res = strcmp(ps1->last,ps2->last);
    if (res != 0)
        return res;
    else
        return strcmp(ps1->first,ps2->first);
}


void generateString(char * dest,int len)
{
    int cnt, randNo;
    for (cnt = 0; cnt     {
        randNo = rand() % 62;
        *dest = allChar[randNo];
        dest++;
    }
    *dest = '\0';
}
 

你可能感兴趣的:(C,Primer,Plus(第六版),c语言,开发语言)