如何以正确的方式转换 void** 指针?
How to cast void** pointer in the correct way?
鉴于
void func(void **structs)
{
UI_Remote_s* a1 = (UI_Remote_s*)structs->Method; //expression
UI_Remote_s* a2 = ((UI_Remote_s*)structs)->Method; //correct
}
第一次尝试是错误的。为什么?
我不会使用这种类型的转换,因为它会使代码更难阅读。而是使用一个临时变量来存储指针。这将使代码更易于阅读和理解。编译器很可能会在生成的代码中对其进行优化。
UI_Remote_s **ptr = (UI_Remote_s **)structs;
a2 = (*ptr) -> Method;
a2 = (*(ptr + 5)) -> Method;
a2 = ptr[2] -> Method;
.....
鉴于
void func(void **structs)
{
UI_Remote_s* a1 = (UI_Remote_s*)structs->Method; //expression
UI_Remote_s* a2 = ((UI_Remote_s*)structs)->Method; //correct
}
第一次尝试是错误的。为什么?
我不会使用这种类型的转换,因为它会使代码更难阅读。而是使用一个临时变量来存储指针。这将使代码更易于阅读和理解。编译器很可能会在生成的代码中对其进行优化。
UI_Remote_s **ptr = (UI_Remote_s **)structs;
a2 = (*ptr) -> Method;
a2 = (*(ptr + 5)) -> Method;
a2 = ptr[2] -> Method;
.....