如何修复C中的“不兼容的指针类型”错误?

时间:2019-04-21 10:05:35

标签: c function pointers

我有关于函数指针的功课,并在C中实现继承。我遇到有关Aralik,VerilenlerArasindan和Harfler的“不兼容的指针类型”错误。怎么了?

  

RastgeleKarakter.h

    struct RASTGELEKARAKTER{
        Random ran;
        char (*Harf)(struct RASTGELEKARAKTER*);
        char* (*Harfler)(struct RASTGELEKARAKTER*);
        char* (*Aralik)(struct RASTGELEKARAKTER*);
        char* (*VerilenlerArasindan)(struct RASTGELEKARAKTER*);
        char* (*Cumle)(struct RASTGELEKARAKTER*);
        void (*YokEt)(struct RASTGELEKARAKTER*);
    };

    typedef struct RASTGELEKARAKTER* RastgeleKarakter;

    RastgeleKarakter RastegeleKarakterOlustur();
    char RandomHarf(RastgeleKarakter);
    char* RandomHarfler(RastgeleKarakter,unsigned);
    char* RandomAralik(RastgeleKarakter,unsigned,char,char);
    char* RandomVerilenlerArasindan(RastgeleKarakter,unsigned,char*);
    char* RandomCumle(RastgeleKarakter);
    void RastgeleKarakterYokEt(RastgeleKarakter);
  

RastgeleKarakter.c

RastgeleKarakter RastegeleKarakterOlustur(){

    RastgeleKarakter karakter;
    karakter = (RastgeleKarakter)malloc(sizeof(struct RASTGELEKARAKTER));
    karakter->ran = RandomOlustur();
    karakter->Harf = &RandomHarf;
    karakter->Harfler = &RandomHarfler;
    karakter->Aralik = &RandomAralik;
    karakter->VerilenlerArasindan = &RandomVerilenlerArasindan;
    karakter->Cumle = &RandomCumle;
    karakter->YokEt = &RastgeleKarakterYokEt;
    return karakter;
}

2 个答案:

答案 0 :(得分:3)

  

警告:来自不兼容的指针类型[-Wincompatible-pointer-types]的赋值       karakter-> Harfler =&RandomHarfler;

因为

  

char *( Harfler)(struct RASTGELEKARAKTER );

但是

  

char * RandomHarfler(RastgeleKarakter,unsigned);

RandomHarfler 得到两个参数,但 Harfler 必须接收指向仅获得struct RASTGELEKARAKTER*

的函数的指针
  

警告:来自不兼容的指针类型[-Wincompatible-pointer-types]的赋值       karakter-> Aralik =&RandomAralik;

因为

  

char *( Aralik)(struct RASTGELEKARAKTER );

但是

  

字符* RandomAralik(RastgeleKarakter,unsigned,char,char);

RandomAralik 获得4个参数,但 Aralik 必须接收指向仅获取struct RASTGELEKARAKTER*

的函数的指针
  

警告:来自不兼容的指针类型[-Wincompatible-pointer-types]的赋值       karakter-> VerilenlerArasindan =&RandomVerilenlerArasindan;

因为

  

char *( VerilenlerArasindan)(struct RASTGELEKARAKTER );

但是

  

char * RandomVerilenlerArasindan(RastgeleKarakter,unsigned,char *);

RandomVerilenlerArasindan 获得3个参数,但 VerilenlerArasindan 必须接收指向仅获得struct RASTGELEKARAKTER*的函数的指针

答案 1 :(得分:2)

Harfler成员被声明为指向使用struct RASTGELEKARAKTER *的函数的指针:

char* (*Harfler)(struct RASTGELEKARAKTER*);

但是您尝试为其分配一个指向RandomHarf的指针:

karakter->Harf = &RandomHarf;

被声明为指向使用struct RASTGELEKARKTER *(通过typedef RastgeleKarakter)和unsigned的函数的指针:

char* RandomHarfler(RastgeleKarakter,unsigned);

指向带有一个参数的函数的指针与指向带有两个参数的函数的指针不兼容。