I have grep function in C( embedded programming ) that takes a void pointer as a parameter. the function needs to be able to handle different kinds of types of variables like chars ints and longs. How can I code the function so it can figure out by itself what type of variable i am passing ?? I dont know if this is possible. thanks
ie.
void grep( void *t )
{
if( t == char )
{
do this
}
if( t == int )
{
do that
}
...
}
It is not possible to do with any accuracy. A 4 byte integer could easily be interpreted as a string for example. For example, a null terminated string "ABC" would be the same as the integer value 1094861568 (depending on byte order).
Void pointer contains just a location in memory where the piece of data is stored. You can't infer any type information from it. But what you can do is, pass two parameters to your function one for the type and another for the pointer.
If you can use C++ you can create a set of overloaded helper functions that will supply the type information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With