Andy Lin
Andy Lin

Reputation: 447

How to cast void** pointer in the correct way?

Given that

void func(void **structs)
{
    
    UI_Remote_s* a1 = (UI_Remote_s*)structs->Method;         //expression 
    UI_Remote_s* a2 = ((UI_Remote_s*)structs)->Method;       //correct
}

The first attempt is wrong. Why?

Upvotes: 0

Views: 113

Answers (1)

0___________
0___________

Reputation: 67476

I would not use this type of casting as it makes code much harder to read. Instead use a temporary variable to store the pointer. It will make the code easier to read and understand. The compiler is very likely to optimize it oout in the generated code.

UI_Remote_s **ptr = (UI_Remote_s **)structs;
a2 = (*ptr) -> Method;
a2 = (*(ptr + 5)) -> Method;
a2 = ptr[2] -> Method;
.....

Upvotes: 2

Related Questions