Skip to main content
gamedev.net
🔒 Locked

easy void * ?

Started by Dwiel Aug 9, 2001 at 11:08 AM 1 replies 250+ views
Original Post
Dwiel
Dwiel
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.
Sandman
Sandman
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.




JungleJim
JungleJim
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

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.