【C语言】18_用qsort函数自定义cmp实现字符串排序

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define MAX_WORDS 100
#define STRLEN 20

/*cmp函数传递两个成员的地址来进行比较。
由于该数组包含 char * 类型的元素,因此这些成员的地址具有 char ** 类型。
而strcmp 函数需要一对 char * ,
因此每个 const void * 参数必须首先转换为 const char ** 的预期类型,
并解引用以获得 strcmp 的正确类型。
如果直接return strcmp(w1, w2)比较的是:
指向字符数组的指针的值,而不是指向字符串的指针的值,
实际比较的是指针地址,而不是字符串的内容,
需要用二级指针解引用才能得到真正的字符串*/
int cmp(const void* w1, const void* w2) {
	return strcmp(*(const char**)w1, *(const char**)w2);
}

int main(void) {
	char* words[MAX_WORDS] = { NULL };
	int len = 0;

	while (1) {
		printf("Enter word: ");
		words[len] = malloc(sizeof(char) * (STRLEN + 1));	//还有\0

		if (!words[len]) {
			printf("Error: malloc failed\n");
			exit(1);
		}
		gets(words[len]);

		if (!strlen(words[len])) break;
		len++;
	}

	qsort(words, len, sizeof(char*), cmp);

	printf("\nIn sorted order: ");
	for (int i = 0; i < len; i++) {
		printf("%s ", words[i]);
	}
	printf("\n");

	for (int i = 0; i < len; i++) {
		free(words[i]);
	}

	return 0;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值