C语言qsort函数

排序qsort

  1. int
c 复制代码
int cmp(const void *a, const void *b)
{
	return *(int *)a - *(int *)b;//先强转成int型,后解引用取值比较大小
}
  1. 字符串数组 char a[] = "hello world" //字符串数组,存放的是字符
c 复制代码
int cmp(const void *a, const void *b)
{
	return *(char*)a - *(char *)b;//实质是转化成ascii值比较;
}
  1. 字符串指针数组排序 char *b[] = { "hello" , "world"};字符串指针数组,存放的是指针即元素地址,指针指向其中的元素
c 复制代码
int cmp(const void *a, const void *b)
{
	return strcmp(*(char **)a, *(char**)b);
  1. 结构体排序
c 复制代码
struct Stu
{
	int age;
	char name[20];
};
//比较结构体中元素的年龄
int cmp_age(const void* e1, const void* e2)
{
	//本质是比较整形
	return ((struct Stu*)e1)->age - ((struct Stu*)e2)->age;
}
//比较名字
int cmp_name(const void* e1, const void* e2)
{
	//本质是字符串比较->使用strcmp函数
	return strcmp(((struct Stu*)e1)->name, ((struct Stu*)e2)->name);
}

补充字符串

  1. 字符串定义:
c 复制代码
char *str1 = {"Hello world!"};  // 方式一 (可省略{})
char str2[] = {"Hello world!"}; // 方式二 (可省略{})
char str3[] = {'H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', '\0'}; // 方式三
char str4[16] = {'H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd', '!', '\0'}; // 方式四
  1. 字符串指针数组
c 复制代码
char* parr[] ={"good head","strength body","smooth foot"} ;

那么数组首元素是char* 类型的,char*类型的地址就是char**是二级指针。

相关推荐
RuoZoe4 天前
重塑WPF辉煌?基于DirectX 12的现代.NET UI框架Jalium
c语言
祈安_8 天前
C语言内存函数
c语言·后端
郑州光合科技余经理9 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1239 天前
matlab画图工具
开发语言·matlab
dustcell.9 天前
haproxy七层代理
java·开发语言·前端
norlan_jame9 天前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone9 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054969 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
czy87874759 天前
除了结构体之外,C语言中还有哪些其他方式可以模拟C++的面向对象编程特性
c语言
遥遥江上月9 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js