Use of qsort function

1. The form of qsort function

1.1 Use the library included with the qsort function

1.2 Parameters of qsort function

qsort: Sort the elements of an array

1.3 Compar function in parameters 

struct stu
{
	char name[20];//姓名
	int age;//年龄
	double grade;//成绩
};
int cmp_name(void* p1, void* p2)
{
	//如果按照姓名排序
	return strcmp(((struct stu*)p1)->name, ((struct stu*)p2)->name);
}
int cmp_age(void* p1, void* p2)
{
	//如果按照年龄排序
	return ((int*)p1 - (int*)p2);
}
int cmp_grade(void* p1, void* p2)
{
	//如果按照成绩排序
	return (int)((double*)p1 - (double*)p2);
}

2. Use of qsort function

From the form of the qsort function, it is not difficult to see that qsort can perform the sorting we need based on the compar function we pass in.

struct stu
{
	char name[20];//姓名
	int age;//年龄
	double grade;//成绩
};
int cmp_name(void* p1, void* p2)
{
	//如果按照姓名排序
	return strcmp(((struct stu*)p1)->name, ((struct stu*)p2)->name);
}
int cmp_age(void* p1, void* p2)
{
	//如果按照年龄排序
	return ((int*)p1 - (int*)p2);
}
int cmp_grade(void* p1, void* p2)
{
	//如果按照成绩排序
	return (int)((double*)p1 - (double*)p2);
}


int main()
{
	struct stu s1 = { "zhangsan",14,89.5 };
	struct stu s2 = { "lisi",17,94.0 };
	struct stu s3 = { "wangwu",45,66.5 };
	struct stu arr[] = { s1,s2, s3 };

	int sz = sizeof(arr) / sizeof(arr[0]);
	qsort(arr, sz, sizeof(arr[0]), cmp_name);
//需要排序的数组   //每个数组元素的大小
          //排序的数组中的元素数     排序所遵循的compar函数名     



	return 0;
}

From debugging we can see that qsort has sorted the array. 

 3. void* pointer

Pointers of type void* cannot be used for dereference operators, nor can they be used for + - integer operations.

A pointer of type void* is used to store the address of any type of data.

void* Pointer without concrete type

You can use a void* pointer to receive any type of pointer. If you need to dereference a void* pointer, you can cast it.

Guess you like

Origin blog.csdn.net/m0_75186846/article/details/132773094