Even though it is possible to write generic code in C using void pointer(generic pointer), I find that it is quite difficult to debug the code since void pointer can take any pointer type without warning from compiler.
(e.g function foo() take void pointer which is supposed to be pointer to struct, but compiler won't complain if char array is passed.)
What kind of approach/strategy do you all use when using void pointer in C?
Generic programming in C with void pointer
cgenericspointers
Related Topic
- C++ – a smart pointer and when should I use one
- C# – How to use reflection to call a generic method
- With arrays, why is it the case that a[5] == 5[a]
- Java – How to create a generic array in Java
- Java – How to get a class instance of generic type T
- C++ – Typedef function pointer
- C++ – What does “dereferencing” a pointer mean
- C++ – use a pointer rather than the object itself
Best Answer
The solution is not to use
void*
unless you really, really have to. The places where a void pointer is actually required are very small: parameters to thread functions, and a handful of others places where you need to pass implementation-specific data through a generic function. In every case, the code that accepts thevoid*
parameter should only accept one data type passed via the void pointer, and the type should be documented in comments and slavishly obeyed by all callers.