C中的函数指针? [英] Function pointer in C?

查看:36
本文介绍了C中的函数指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 C 语言初学者,正在学习 C 语言中的函数指针.在那里我遇到了问题?

I am beginner in C language and was learning about function pointer in C language. There I encountered a problem?

写一个比较函数来按名字的第一个字符排序?

Write a compare function to sort by first character of name?

*int (firstnamecharcompar)(const void * a, const void * b))

*int (firstnamecharcompar)(const void * a, const void * b))

这是我的代码解决方案.

Here is my code solution for this.

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

int compare1(const void *a,const void *b)
{
    char *c = *(char**)a;
    char *d = *(char**)b;
    return c[0] - d[0];                             
    //return ( *(char*)a[0] == *(char*)b[0] );                
}

int main()
{
    char* str[3];
    int i;
    for(i=0;i<3;i++)
    {
        str[i] = (char*)malloc(10*sizeof(char));
    }
    for(i=0;i<3;i++)
    {
        printf("Enter %d string => " , i+1 );
        scanf("%s", str[i]);                        
        printf("\n");
    }
    
    for(i=0;i<3;i++)
    {
        printf("%s ",str[i]);
    }
    
    qsort(str,3,10,compare1);
    
    for(i=0;i<3;i++)
    {
        printf("%s ",str[i]);
    }
    return 0;
}

但是我的代码在没有给出任何输出的情况下被终止了?我的代码有什么问题?

But my code is getting terminated without giving any output? What is problem with my code?

推荐答案

qsort(str,3,10,compare1); 错误.

您正在对指针数组进行排序.您需要传入指针的大小,而不是它指向的对象的大小.也就是说,sizeof(char*) 而不是 10.

You are sorting an array of pointers. You need to pass in the size of the pointer, not the size of the object it is pointing to. That is, sizeof(char*) rather than 10.

这篇关于C中的函数指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆