Search code examples
ccastingoperator-precedence

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?


Solution

  • 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;
    .....