【问题标题】:In function - Error: Assignment from incompatible pointer type [-Werror=incompatible-pointer-types]在函数中 - 错误:来自不兼容指针类型的赋值 [-Werror=incompatible-pointer-types]
【发布时间】:2021-11-16 06:28:47
【问题描述】:

您好,我正在初始化一个函数指针以替换布尔函数中的 switch 语句。所以我想使用结构的成员并将布尔函数的地址分配/复制给该成员。我后来的计划是移除开关盒并使用函数指针来处理特定类型(TYPE_A...等)

//Declaration of typedef as a boolean 
typedef bool (*tone_function_t) (state_t *state, u8_t type);

//typedef structure
typedef struct node {
    tone_function_t tone;
} node_t;

bool_t tone(state_t *state, u8_t type) {
    switch (type) {
        case TYPE_A :
        case TYPE_B :
        case TYPE_C :
        case TYPE_D :
        case TYPE_E :
            return TRUE;
    }
  
    return FALSE;
}

int main(state_t *state) {
    node_t node;
    node.tone = &tone; //Compilation Error : assignment from incompatible pointer type. Am i doing any mistake here??
    return 0;
}

在将布尔函数的地址分配给结构的成员时,我遇到了编译错误。有什么线索可以解决这个问题吗? node->tone 也是一种错误的初始化方式。 尝试过 memcpy 或 malloc。它并没有真正起作用。

提前致谢!

【问题讨论】:

    标签: c pointers struct typedef


    【解决方案1】:

    tone 函数与指针类型不匹配。

    tone 被声明返回 bool_t 但函数指针类型 tone_function_t 返回 bool

    更改两者之一,使返回类型匹配。

    【讨论】:

    • 即使更改后我仍然有相同的编译错误。
    • @revanth 然后还有更多你没有向我们展示的内容。请使用minimal reproducible example 更新您的代码,其他人无需修改即可编译以获得与您相同的结果。
    • 您的回答是正确的。我在代码中试验新东西,忘记了一些要改回来的东西,例如:tone_function_t *tone; (现在删除 *)现在它工作了。谢谢:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-09
    • 1970-01-01
    • 2019-08-09
    • 2017-10-24
    • 1970-01-01
    • 1970-01-01
    • 2014-07-27
    相关资源
    最近更新 更多