2015-10-06 39 views
9

以下是Richard Reese的“了解和使用C指针”的示例。 我的问题是它应该是“typedef int(* fptrOperation)......”在第7行吗? 我尝试了他们两个,但他们都运作良好。我搜索了使用typedef和指针在线两天的功能,但仍然没有弄明白。 感谢您的任何帮助~~typedef和指向C中的函数

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


typedef int (fptrOperation)(const char*, const char*);// 


char* stringToLower(const char* string) { 
    char *tmp = (char*) malloc(strlen(string) + 1); 
    char *start = tmp; 
    while (*string != 0) { 
     *tmp++ = tolower(*string++); 
    } 
    *tmp = 0; 
    return start; 
}  

int compare(const char* s1, const char* s2) { 
    return strcmp(s1,s2); 
}  

int compareIgnoreCase(const char* s1, const char* s2) { 
    char* t1 = stringToLower(s1); 
    char* t2 = stringToLower(s2); 
    int result = strcmp(t1, t2); 
    free(t1); 
    free(t2); 
    return result; 
}  



void displayNames(char* names[], int size) { 
    for(int i=0; i<size; i++) { 
    printf("%s ",names[i]); 
    } 
    printf("\n"); 
}  

void sort(char *array[], int size, fptrOperation operation) { 
    int swap = 1; 
    while(swap) { 
     swap = 0; 
     for(int i=0; i<size-1; i++) { 
      if(operation(array[i],array[i+1]) > 0){ 
       swap = 1; 
       char *tmp = array[i]; 
       array[i] = array[i+1]; 
       array[i+1] = tmp; 
      } 
     } 
    } 
}  





int main(int argc, char const *argv[]) 
{ 
    char* names[] = {"Bob", "Ted", "Carol", "Alice", "alice"}; 
    sort(names,5,compareIgnoreCase); 
    displayNames(names,5);  

    return 0; 
}  
+2

https://stackoverflow.com/questions/17914057/is-an-asterisk-optional-in-a-function-指针 –

+0

带有-Wall选项的gcc没有警告,我想对于如何声明函数指针没有限制。编译器自己做这个魔术,因为当编译sort(names,5,compareIgnoreCase);'时,没有其他方式使用'compareIgnoreCase'的地址。 – LPs

回答

5

没关系。

这是因为函数的参数,功能类型被自动转换为指针到功能(ISO/IEC 9899:2011,6.7.6.3,§8):

一个参数的声明为“”函数返回类型''应调整为''指向函数返回类型'',如6.3.2.1所示。

3

C99 6.3.2.1左值,数组和功能指示符:

4所述的功能标志是具有功能类型的表达式。 除了它是sizeof运算符的操作数或一元运算符以外,函数返回类型为' '的函数指示符被转换为一个表达式,该表达式的类型指针指向功能 ,返回类型为''。

6.5.3.2地址和间接运算符:

4一元运算符*表示间接。如果操作数指向一个 函数,则结果是一个函数指示符;

6.7.5.3功能说明符(包括原型):

8的参数为“”函数返回类型“”应 调整为“的声明”函数指针返回类型“”如6.3.2.1所述。

所以,你的榜样,甚至以下所有有效:

#include <stdio.h> 

void foo(void) 
{ 
    puts("foo"); 
} 

int main(void) 
{ 
    foo(); 
    (&foo)(); 
    (*foo)(); 
    return 0; 
}