2015-10-06 41 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; 
}