Reputation: 10433
I am trying to
void*
from a method for int
When I am doing this directly, like passing &x to the conversion method it returns correct value, but through method call I am getting weird number.
here is the code...
void *GetVoidPointer(int a)
{
return &a;
}
int ReadValueFromVoidPointer(void *ptr)
{
int *i = static_cast<int*>(ptr);
return *i;
}
int main()
{
int x = 10;
//Through method call to get void* : This doesn't work
int i= ReadValueFromVoidPointer(GetVoidPointer(x));
printf("%d\n", i);
//Direct call : This works
int y= ReadValueFromVoidPointer(&x);
printf("%d\n", y);
return 0;
}
I am very new to C++ so might be doing something very silly. Please advise.
Upvotes: 1
Views: 149
Reputation: 1251
When compiling your code you receive the following error :
test.cpp: In function ‘void* GetVoidPointer(int)’:
test.cpp:4:26: warning: address of local variable ‘a’ returned [-Wreturn-local-addr]
void *GetVoidPointer(int a)
It means that your are returning the adress of a local variable (a
), which is a problem as this variable is removed at the end of the function call.
Therefore you have to pass a reference
to it (I'll let you look for some detailed explanations about it...).
So you just have to change the GetVoidPointer()
by the following and everything is OK : void *GetVoidPointer(int& a)
.
The result values are 10
and 10
.
I'm using the compile g++
in version 8.3.0
with no added options.
Upvotes: 4
Reputation: 870
In function GetVoidPointer, the local param 'a' is temporary. When GetVoidPointer returned, 'a' will be destroyed by the system. So, you will not get the correct value. You could use 'C++ reference'.
Upvotes: 0