m0_62667564 2022-03-19 22:01 采纳率: 84.8%
浏览 29
已结题

有关函数指针的使用方法

分别对字符串(112和12)按编码和数字进行比较。
在sort()函数中,参数要求为:传递字符串数组、数组大小和字符串比较的函数指针。
最后一个要求字符串比较的函数指针是怎么写的呢?麻烦顺着我的思路写一下,还需要定义什么函数吗,帮我补齐一下,谢谢

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

int compare_by_ascii(const chars1,const chars2);
int compare_by_digits(const chars1,const chars2);

void main()
{
char*strs[2]={"112","12"};
sort(strs,2,compare_by_ascii);
sort(strs,2,compare_by_digits);
}

sort(const char*strs[],int n,这里应该怎么写? )
{
int i,j;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if

int compare_by_ascii(const chars1,const chars2)
{
return strcmp(s1,s2);
}

int compare_by_digits(const chars1,const chars2)
{
int v1=atoi(s1);
int v2=atoi(s2);
if(s1>s2)
{
return 1;
}
else if(v1==v2)
{
return 0;
}
else
return -1;
}

  • 写回答

2条回答 默认 最新

  • 关注

    你题目的解答代码如下:

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    int compare_by_ascii(const char *s1,const char *s2);
    int compare_by_digits(const char *s1, const char *s2);
    
    void sort(char *strs[], int n, int (*fp)(const char *s1, const char *s2))
    {
        int i, j;
        char *t;
        for (i = 0; i < n-1; i++)
        {
            for (j = i + 1; j < n; j++)
            {
                if(fp(strs[i], strs[j])>0)
                    {
                        t = strs[i];
                        strs[i] = strs[j];
                        strs[j] = t;
                    }
            }
        }
    }
    
    
    
    int compare_by_digits(const char *s1, const char *s2)
    {
        int v1 = atoi(s1);
        int v2 = atoi(s2);
        if (v1 > v2)
        {
            return 1;
        }
        else if (v1 == v2)
        {
            return 0;
        }
        else
            return -1;
    }
    int compare_by_ascii(const char *s1, const char *s2)
    {
        return strcmp(s1,s2);
    }
    
    void main()
    {
        char *strs[4] = {"112", "12", "31", "2"};
        sort(strs, 4, compare_by_ascii);
        for (int i = 0; i < 4; i++)
        {
            printf("%s\n", strs[i]);
        }
        sort(strs, 4, compare_by_digits);
        for (int i = 0; i < 4; i++)
        {
            printf("%s\n", strs[i]);
        }
    
    }
    

    如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!

    img

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 3月28日
  • 已采纳回答 3月20日
  • 创建了问题 3月19日

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog