c primer plus 第十六章课后编程6题

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NUM 40
struct names {
char last[NUM];
char first[NUM];
};

void showarray(const struct names ar[],int n);
int mycomp(const void * p1, const void * p2);

int main(void)
{
struct names vals[5]={
{“Wang”,“xiaopeng”},
{“Wang”,“xiaoqiang”},
{“Wang”,“jinxuan”},
{“Liang”,“jianhui”},
{“Liang”,“tinyu”},
};

puts("Random list:");
showarray(vals, 5);
qsort(vals, 5, sizeof(struct names),mycomp);
puts("\nSorted list:");
showarray(vals, 5);
return 0;

}

void showarray(const struct names ar[],int n)
{
int index;

for(index=0; index<n; index++)
    printf("%s %s\n",ar[index].first,ar[index].last);

}

int mycomp(const void *p1, const void * p2)
{
const struct names *a1 = (const struct names *) p1;
const struct names *a2 = (const struct names *) p2;
int res;
res = strcmp(a1->last, a2->last);
if(res!=0)
return res;
else
return strcmp(a1->first, a2->first);
}

发布了85 篇原创文章 · 获赞 1 · 访问量 1889

猜你喜欢

转载自blog.csdn.net/Tekkenwxp/article/details/103340220