Getting a value from a pointer
I have a problem getting a value from a pointer. I have the following code in C ++:
void* Nodo::readArray(VarHash& var, string varName, int posicion, float& d)
{
//some code before...
void* res;
float num = bit.getFloatFromArray(arregloTemp); //THIS FUNCTION RETURN A FLOAT AND IT OK
cout << "NUMBER " << num << endl;
d = num;
res = #
return res
}
int main()
{
float d = 0.0;
void* res = n.readArray(v, "c", 0, d); //THE VALUES OF THE ARRAY ARE: {65.5, 66.5};
float* car3 = (float*)res;
cout << "RESULT_READARRAY " << *car3 << endl;
cout << "FLOAT REFERENCE: " << d << endl;
}
The result of running this code is the following:
NUMBER 65.5 RESULT_READARRAY -1.2001
// WRONG, IT SHOULD BE A
FLOAT REFERENCE NUMBER : 65.5 // CORRECTNUMBER 66.5 RESULT_READARRAY -1.2001
// WRONG, IT SHOULD BE
FLOAT REFERENCE NUMBER : 66.5 // CORRECT
For some reason, when I get the pointer value returned by the readArray function is wrong. I am passing the float (d) variable as a reference in the same function to make sure the value is ok and as you can see the FLOAT REFERENCE is NUMBER. If I declare the num (read array) variable as a static float, the first RESULT_READARRAY will be 65.5, which is correct, however the next value will be the same, not 66.5. Let me show you the result of running the code with a static float variable:
NUMBER 65.5 RESULT_READARRAY 65.5
// PERFECT FLOAT REFERENCE: 65.5
// ¨PERFECTNUMBER 65.5 // THIS IS WRONG IT
SHOULD BE 66.5 RESULT_READARRAY 65.5
FLOAT REFERENCE: 65.5
Do you know how I can get the correct value returned by the readArray () function?
a source to share
You are returning a pointer to a stack variable (local variable) that expires after you leave this function. He called the hanging pointer .
One way to solve the problem would be to use
float *num = new float(bit.getFloatFromArray(arregloTemp);
// ...
return (void*)num;
which would force it num
to be allocated on the heap, allowing the pointer to be used after the function exits.
But the best option for the example above would be to just return readArray
a float
and return the value num
. You don't seem to get anything by returning a pointer here.
a source to share
The variable num
was declared inside the scope, on the stack. Once the function returns that the memory location is no longer available, and although you can most likely get it, it will (usually) not store the desired value. This is a mistake anyway.
To fix this, you can:
- dynamically allocate this memory and release it later
- returns a value directly, not a pointer
a source to share