Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Void pointer question

Tags:

c

pointers

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  
   }  
   ... 
}
like image 905
jramirez Avatar asked Jul 07 '10 20:07

jramirez


2 Answers

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).

like image 81
Mark Wilkins Avatar answered Sep 29 '22 12:09

Mark Wilkins


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.

like image 43
Vlad Avatar answered Sep 29 '22 11:09

Vlad