Getting value from pointer

Posted by Eric on Stack Overflow See other posts from Stack Overflow or by Eric
Published on 2010-05-04T16:31:37Z Indexed on 2010/05/04 16:38 UTC
Read the original article Hit count: 287

Filed under:
|

Hi,

I'm having problem getting the 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'S OK  
    cout << "NUMBER " << num << endl;            
    d = num;  
    res = &num;  
    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
//INCORRECT IT SHOULD BE LIKE NUMBER
FLOAT REFERENCE: 65.5 //CORRECT

NUMBER 66.5 RESULT_READARRAY -1.2001
//INCORRECT IT SHOULD BE LIKE NUMBER
FLOAT REFERENCE: 66.5 //CORRECT

For some reason, when I get the value of the pointer returned by the function called readArray is incorrect. I'm passing a float variable(d) as a reference in the same function just to verify that the value is ok, and as you can see, THE FLOAT REFERENCE matches the NUMBER. If I declare the variable num(read array) as a static float, the first RESULT_READARRAY will be 65.5, that is correct, however, the next value will be the same instead of 66.5. Let me show you the result of running the code using static float variable:

NUMBER 65.5 RESULT_READARRAY 65.5
//PERFECT FLOAT REFERENCE: 65.5
//¨PERFECT

NUMBER 65.5 //THIS IS INCORRECT, IT
SHOULD BE 66.5 RESULT_READARRAY 65.5
FLOAT REFERENCE: 65.5

Do you know how can I get the correct value returned by the function called readArray()?

© Stack Overflow or respective owner

Related posts about pointers

Related posts about c++