-3

関数ポインターを使用して文字列を比較するコードを作成しました。しかし、エラーが表示され、修正方法がわかりません。コードは次のとおりです。

#include<stdio.h>
#include<string.h>
void sports_no_bieber(char *);  
void science_sports(char *);
void theater_no_guys(char *);
int find(int(*match)(char*)); 
int NUM_ADS=4;
char *ADS[]={
                "Sarah:girls, sports, science",
                "William: sports, TV, dining",
                "Matt: art, movies, theater",
                "Luis: books, theater, guys",
                "Josh: sports, movies, theater"
            };
int main()
{
printf("Bachelorette Amanda needs your help! He wants someone who likes sports but not  bieber.\n");
find(sports_no_bieber);
printf("Bachelorette Susan needs your help! She wants someone who likes science and sports. (And girls).\n");
find(science_sports);
printf("Bachelorette Emily needs your help! She wants someone who likes theater but not guys.\n");
find(theater_no_guys);
return 0;
}



int find(int(*match)(char* ))
{
        int i;
      puts("Search results\n");
puts("--------------------");
for(i=0;i<NUM_ADS;i++)
{
    if(match(ADS[i]))
        printf("%s\n",ADS[i];
}
puts("--------------------");
return i;
}

int sports_no_bieber(char * s)
{
return  (strstr(s, "sports")) && (!strstr (s,"bieber") );
}

int science_sports(char * s)
{
return  (strstr(s, "science")) && (strstr (s,"sports" ));
}

int theater_no_guys(char * s)
{
return (strstr(s, "theater"))&&(!strstr(s,"guys"));
}

そしてそれが示すエラーは

E:\ComputerPrograming\FunctionPointer.c: In function `int main()':
E:\ComputerPrograming\FunctionPointer.c:18: passing `void (*)(char *)' as argument 1 of `find(int (*)(char *))'
E:\ComputerPrograming\FunctionPointer.c:20: passing `void (*)(char *)' as argument 1 of `find(int (*)(char *))'
E:\ComputerPrograming\FunctionPointer.c:22: passing `void (*)(char *)' as argument 1 of `find(int (*)(char *))'
E:\ComputerPrograming\FunctionPointer.c: In function `int find(int (*)(char *))':
E:\ComputerPrograming\FunctionPointer.c:36: parse error before `;'
E:\ComputerPrograming\FunctionPointer.c:40: confused by earlier errors, bailing out

find 関数を int 関数にしようとさえしました...しかし、それは何の違いもありませんでした。エラーは正確には何を意味しますか?

4

2 に答える 2

4

これらの関数宣言:

void sports_no_bieber(char *);  
void science_sports(char *);
void theater_no_guys(char *);

find()が必要とする関数ポインタのシグネチャまたはその定義と一致しません。への変更:

int sports_no_bieber(char *);  
int science_sports(char *);
int theater_no_guys(char *);

NUM_ADSは配列内の要素の数と等しくないことに注意してくださいADS: 1 つ少ないです。ポインターで配列を確実NUM_ADSADS終了し、それをループ終了条件として使用する (および破棄する)必要がないようにするには、次のようにします。NUM_ADSNULLNUM_ADS

const char *ADS[] =
{
    "Sarah:girls, sports, science",
    "William: sports, TV, dining",
    "Matt: art, movies, theater",
    "Luis: books, theater, guys",
    "Josh: sports, movies, theater",
    NULL
};

for(int i=0; ADS[i]; i++)
{

どの関数もコンテンツを変更したり、ポインターを再割り当てしたりしないため、すべての関数の引数の型をconst char* constの代わりにすることを提案します。char*

于 2013-05-08T12:37:34.663 に答える