gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:16:40 24 4
gpt4 key购买 nike

我有一个函数指针,其函数被声明为期望 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/

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