【发布时间】:2021-12-27 18:06:28
【问题描述】:
如果在示例函数转换中出现并且调用在 C 中有效,我正在寻找答案(如果没有任何示例,如何获得类似的行为会很好)。
例子:
#include <stdio.h>
#include <stdint.h>
typedef struct {
uint32_t a;
} parent_t;
typedef struct {
parent_t parent;
uint32_t b;
} child_t;
typedef void (*funct_ptr_t)(parent_t* pParent, uint32_t x);
void test_function(child_t* pChild, uint32_t x);
int main()
{
funct_ptr_t func = (funct_ptr_t)test_function;
funct(NULL, 0U);
return 0;
}
void test_function(child_t* pChild, uint32_t x) {
// do something
}
@编辑 如上无效,我也想问一下第二种方法
typedef void (*funct_ptr_t)(void* pChild, uint32_t x);
void test_function(child_t* pChild, uint32_t x);
int main()
{
funct_ptr_t func = (funct_ptr_t)test_function;
child_t child;
func(&child, 0U);
return 0;
}
void test_function(child_t* pChild, uint32_t x) {
// do something
}
【问题讨论】:
-
这至少看起来很危险 - 该函数需要一个指向
child_t对象的指针,但可能会收到一个“仅”指向parent_t的指针。如果该函数随后尝试访问b成员,您肯定会调用 undefined behavior -
相反的做法是安全的,因为该函数不会尝试访问
parent前缀。
标签: c language-lawyer