gpt4 book ai didi

转换函数指针

转载 作者:行者123 更新时间:2023-12-04 13:03:23 25 4
gpt4 key购买 nike

如果我有一个原型(prototype)声明为:

void foo(int (*fi)(void *, void *))

我用这样的方式调用函数:

foo(int (*)(void*, void*)(bool_expr ? func1 : func2));

其中func1和func2定义如下:

int func1(char *s1, char *s2);
int func2(int *i1, int *i2);

函数调用是否将其中一个函数 (func1 ^ func2) 强制转换为 foo 所需的函数类型?我也可以让 foo 的原型(prototype)看起来像这样吗:

void foo(int (*)(void *, void *))

最佳答案

根据 C 规范,强制转换函数指针会导致未指定的行为,但许多编译器(例如 gcc)会按照您的期望进行操作,因为函数指针只是内存中的一个地址。为了安全起见,我会重新声明 func1 和 func2 为 void*,然后根据需要将这些指针转换为 char* 和 int*。

关于转换函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8334423/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com