typedef函数指针 - >从不兼容的指针类型初始化

时间:2014-09-30 12:26:45

标签: c struct function-pointers typedef compiler-warnings

我无法理解此警告的原因:

menu-file-select.c:41:29: warning: initialization from incompatible pointer type

违规代码是:

typedef int (*FileSelectFilter)(const char*, struct dirent*);

typedef struct {
    const char *dir; //the directory path to read
    const char *out; //where to copy the selected path
    int outLen; //length of out buffer
    FileSelectFilter *filter; //optional filter function
} FileSelectParams;

void showFileSelectMenu(FileSelectParams *params) {
    /* ... */
    FileSelectFilter filter = params->filter; // <-- warning generated here.
    if(filter && !filter(path, ent)) continue;
    /* ... */
}

int main(int argc, char **argv) {
    /* ... */
    FileSelectParams fsel = {
        .dir    = setting.lastpath,
        .out    = RomPath,
        .outLen = sizeof(RomPath) - 1,
        .filter = FileSelectFilter_Roms,
    };
    showFileSelectMenu(&fsel);
    /* ... */
}

int FileSelectFilter_Roms(const char *path, struct dirent *file) {
    /* ... */
}

据我所知,FileSelectFilter_RomsFileSelectFilter typedef匹配,所以我不明白为什么我被告知类型不兼容。该程序似乎无论如何都有效,但是这个警告让我感到困扰。

1 个答案:

答案 0 :(得分:3)

您已将FileSelectFilter定义为typedef中函数的指针:

typedef int (*FileSelectFilter)(const char*, struct dirent*);

FileSelectPararms中,您将filter成员定义为:

FileSelectFilter *filter;

这意味着filter实际上是指向函数指针的指针。这就是您在作业FileSelectFilter filter = params->filter;中收到错误的原因。

filter成员应简单地定义为:

FileSelectFilter filter;