什么是各种风格的定义函数返回一个函数指针

什么是各种风格的定义函数返回一个函数指针

本文介绍了什么是各种风格的定义函数返回一个函数指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个功能:

int compare(char * c1, char * c2){
...
...
}

什么是我可以写一个函数的各种风格的 INT ret_compare(void *的项目)返回一个指针进行对比?

What are the various styles in which I can write a function int ret_compare(void * item) that returns a pointer to compare?

推荐答案

有两种主要方式,一是使用的typedef 和一个没有(有两种变体的的typedef )。您的比较应该不断的指针,如下:

There are two main styles, one using a typedef and one not (with two variants of the typedef). Your comparator should take constant pointers, as below:

int compare(const char *c1, const char *c2) { ... }

// Raw definition of a function returning a pointer to a function that returns an int
// and takes two constant char pointers as arguments
int (*ret_compare1(void *item))(const char *, const char *)
{
    // Unused argument - item
    return compare;
}

// More usual typedef; a Comparator2 is a pointer to a function that returns an int
// and takes two constant char pointers as arguments
typedef int (*Comparator2)(const char *, const char *);

// And ret_compare2 is a function returning a Comparator2
Comparator2 ret_compare2(void *item)
{
    // Unused argument - item
    return compare;
}

// Less usual typedef; a Comparator3 is a function that returns an int
// and takes two constant char pointers as arguments
typedef int Comparator3(const char *, const char *);

// And ret_compare3 is a function returning a pointer to a Comparator3
Comparator3 *ret_compare3(void *item)
{
    // Unused argument - item
    return compare;
}


请注意,这些比较器不能用使用bsearch()的qsort()(除非你使用相当可怕蒙上),因为这些比较预期采取的常量无效* 参数。


Note that these comparators cannot be used with bsearch() and qsort() (unless you use fairly gruesome casts) because those comparators are expected to take const void * arguments.

请注意,那就是,对于比较字符串,而不是单个字符,使用函数的qsort() bsearch()应该是类似于:

Note, too, that for comparing strings, as opposed to single characters, the function used by qsort() or bsearch() should be similar to:

int string_comparator(const void *v1, const void *v2)
{
    const char *s1 = *(char **)v1;
    const char *s2 = *(char **)v2;
    return(strcmp(s1, s2));
}

这篇关于什么是各种风格的定义函数返回一个函数指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 14:10