Archived

This topic is now archived and is closed to further replies.

Dwiel

easy void * ?

Recommended Posts

How do I convert a float to a void *? I have a variable of type void *, and I have a function strtofloat(char string[64]) that returns float. I want the return value of strtofloat to be stored in the void * variable. Thanx ahead for helping newbies like myself.

Share this post


Link to post
Share on other sites
The easiest way is just to make the void* point at the float...

  
float f,g;

// make v point at f...

void* v = &f;

// get the value back out of v

g = *(float*)v;


If you really have to store the value of the float in the void*, it is very difficult (impossible?) to do with straight casting, easier to use memcpy()..

  
memcpy(&v,&f,sizeof(float)); // copy the data to the void* ptr


memcpy(&g,&v,sizeof(float)); // copy the data back to a float.




Share this post


Link to post
Share on other sites
Why would you want to convert a float to a void*? If you want to pass it to some function that accepts a void*, taking the address of the float variable should be enough. Messing with void* is to be avoided (pun intended

Another tip: instead of strtofloat(char string[64]), declare it as strtofloat(const char* str). Specifying the string parameter as a char array of length 64 is not much use, since it will be converted to char* anyway (in standard C). A pointer to a character is sufficient. The const tells that the function doesn''t modify the string.

HTH,
Erik

Share this post


Link to post
Share on other sites