c - 传递 `int (*)(char const*)`,其中应为 `int (*)(char*)`

标签 c pointers function-pointers

我有一个函数指针,其函数被声明为期望 char * arguments.Into 它,我想保存一个指向声明为采用 char const* 的函数的指针参数。

我想我可以使用包装器或类型转换。 转换看起来更直接,但我可以合法地调用这样一个函数指针转换的结果吗?

示例代码如下:

static int write_a(char * X){
    return 0;
}

static int write_b(char const* X){
    return 0;
}
static int wrapped_write_b(char * X){
    return write_b(X);
}

typedef int (*write_fn)(char * );

write_fn a = write_a;
write_fn b = wrapped_write_b;
write_fn b1 = (write_fn)write_b; //is b1 legally callable?

最佳答案

这是未定义的行为 - 只有当类型兼容时,您才能使用指针调用另一种类型的函数 ( 6.3.2.3/8):

A pointer to a function of one type may be converted to a pointer to a function of another type and back again; the result shall compare equal to the original pointer. If a converted pointer is used to call a function whose type is not compatible with the referenced type, the behavior is undefined.

如果(简化版本)两个函数具有相同的返回值且参数兼容( 6.7.6.3 , Semantics/15),则它们具有兼容的类型:

For two function types to be compatible, both shall specify compatible return types.146) Moreover, the parameter type lists, if both are present, shall agree in the number of parameters and in use of the ellipsis terminator; corresponding parameters shall have compatible types.

A const char *char * 不兼容( 6.7.6.1 ,语义/2):

For two pointer types to be compatible, both shall be identically qualified and both shall be pointers to compatible types.

const char *char *不完全合格,它们不兼容,并且调用 write_b通过b是未定义的行为。

关于c - 传递 `int (*)(char const*)`,其中应为 `int (*)(char*)`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40913231/

相关文章:

c++ - 在另一个结构中使用对结构的引用时Arduino编译错误

c++ - 使用指向非静态成员函数的指针实现回调

C、创建进程并等待

c - 在 fork 卡在未知位置的读取循环中后从子管道读取

c - 在 gtk 中出现断言失败错误。

pointers - GO - 隐式方法如何工作?

c - 在 ANSI C 中使用指针替换字符

c++ - 指向成员函数的函数指针

C++ 自己的观察者模式

在 C 中将立体声 wav 转换为单声道