void sort_Chars(Chars arr [], Uint arrLen, int (* compChars)(const char *, Uint, const char *, Uint));
图片为申明
chars是一个结构体
根据提供的资料,写了一个实现, 供参考:
参考链接:
https://blog.csdn.net/weixin_42979760/article/details/125590028
#include <stdio.h>
#include <string.h>
typedef unsigned int Uint;
typedef struct chars {
char * addr;
Uint len;
} Chars;
int comp_chars(const char *s1, Uint len1, const char *s2, Uint len2) {
int d;
const char *st1=s1;
const char *st2=s2;
while(*s1==*s2) {
if(s1==(st1+len1-1)||s2==(st2+len2-1))
break;
s1++;
s2++;
}
d=*s1-*s2;
if(d<0)
return -1;
if (d==0)
return 0;
if(d>0)
return 1;
}
void sort_Chars(Chars arr [], Uint arrLen, int (* compChars)(const char *, Uint, const char *, Uint)){
Uint i,j,tlen;
char temp[100];
// 使用函数指针compChars指向的函数 排序结构数组arr里的元素
for(i=0;i<arrLen-1;i++){
for(j=i+1;j<arrLen;j++){
int compResult = (*compChars)(arr[i].addr,arr[i].len,arr[j].addr,arr[j].len);
// printf("compResult=%d,i=%u,j=%u\n",compResult,i,j);
if(compResult>0){ // 如果比较结果大于0,则交换i和j位置的结构的字段,达到排序的目的
strcpy(temp,arr[i].addr);
strcpy(arr[i].addr,arr[j].addr);
strcpy(arr[j].addr,temp);
tlen = arr[i].len;
arr[i].len = arr[j].len;
arr[j].len = tlen;
}
}
}
}
int main(void){
int i;
int (* compChars)(const char *, Uint, const char *, Uint)= comp_chars;
Chars arr[5];
char cs[5][20]={"today is good day","super man","good good study","abcdefg","xyz is end"};
依次
// 给结构数组5个元素赋值
arr[0].addr = cs[0];
arr[0].len = strlen(arr[0].addr);
arr[1].addr = cs[1];
arr[1].len = strlen(arr[1].addr);
arr[2].addr = cs[2];
arr[2].len = strlen(arr[2].addr);
arr[3].addr = cs[3];
arr[3].len = strlen(arr[3].addr);
arr[4].addr = cs[4];
arr[4].len = strlen(arr[4].addr);
printf("排序前:\n");
for(i=0;i<5;i++){
// https://blog.csdn.net/weixin_42979760/article/details/125590028
printf("%s , %u\n",arr[i].addr,arr[i].len);
}
// 调用 sort_Chars()函数排序结构数组arr的元素
sort_Chars(arr,5,compChars) ;
printf("排序后:\n");
for(i=0;i<5;i++){
printf("%s , %u\n",arr[i].addr,arr[i].len);
}
}