I'm trying to return a float value but when I print it out, I get 0.0.
float floating = 4.5;
void* function(){
void* test = &floating;
return test;
}
int _tmain(int argc, _TCHAR* argv[]){
printf("%f\n", test());
return 0;
}
Any ideas on why it's not printing out 4.5? Sorry if this is a noob question, I'm still fairly new to this.
Assuming your function() is actually spelled as test(), %f expects a float value. You're supplying a void *. It's wrong and undefined behaviour.
Solution: void being an incomplete type, you cannot dereference a void pointer directly. You need to cast the pointer to the required type before dereferencing. For example,
printf("%f\n", *( (float *) test() ) );
Try
printf("%f\n", *( (float*)function() ));
Trying to provide a bit more details about that:
First, from how you phrased your question, you should understand that pointers don't store values, they store addresses of objects. void is no type at all, and a void * pointer might store the address of anything (as long as it's data, but I don't want to overcomplicate my answer right here).
That's probably where you came from in the first place. But then you made two mistakes:
The %f format specifier of printf() doesn't expect a pointer, it expects a value. There's one operation called dereferencing a pointer that fetches the value the pointer points to. In c expressions, you have the dereferencing operator written as an asterisk (*) in front of your value to do that.
So how can you read a value without knowing the type? You can't! That's why dereferencing a void * pointer is illegal. Means, even if you didn't forget the asterisk and wrote for example printf("%f\n", *(test()));, the code would be wrong (and this time, your compiler would catch the error).
That being said, void * pointers in c are meant as a generic pointer and are therefore implicitly convertible to and from any other data pointer type (note this is different in c++). So one way to write your program correctly would be:
int _tmain(int argc, _TCHAR* argv[]){
float *f = test();
printf("%f\n", *f);
return 0;
}
edit: From the fact that void * is implicitly convertible to/from other data pointer types follows your test() could be as simple as that:
void *test()
{
return &floating;
}
edit2: As you're new to pointers, adding an advice not directly related to your question: In a variable declaration in c, the asterisk binds to the identifier (variable name), not to the type. This means you read int * foo; not as "foo is a variable of type pointer to int" but as "foo is a pointer variable of type int". This has a serious implication when writing e.g. int * foo, bar; -- foo will be a pointer, bar a normal variable. Therefore the advice is: make it explicit by writing e.g. void *test instead of void* test.