How to pass a double pointer as an argument and return it from the C ++ function

1

I have a function that requires it to be void and that a double pointer is returned from it by the argument.

void cracking::decompose(char input[][100], int size_S, double* &Atm, int* &ID, int &size_out);
{
vector<double> AtmD;
vector<int> XsD;
...


    Atm = &AtmD[0];
    ID = &XsD[0];
    size_out = size(AtmD);

}

On Main it stays:

int main()
{
    char oi[900][100] = { "1  0.5 C", "2  0.55 N", "3  .5  S" };
    double* xAtm = NULL;
    int* xXs = NULL;
    int tamanho;
    cracking calc;


    calc.decompose(oi, 3, xAtm, xXs, tamanho);



    return 0;
}

Although compiling it returns me completely wrong values. Is there any way to do this with the pointers?

In fact I realized that the pointers inside my function turn into junk when I return them to the main. Is there any way to keep pointers saved? For example, if I save the address 0x000000000029d680 in memory and it corresponds to 23.5, when I leave the function this address no longer corresponds to that value and turns to garbage, is there a way to keep this value?

    
asked by anonymous 12.04.2018 / 19:38

1 answer

0

The point is that both vector<double> AtmD; and vector<int> XsD; are allocated on the stack when your decompose method is called. As soon as this method returns, the function context is destroyed just like the two allocated vectors. So these addresses point to junk.

If you really need to do this, you can allocate an array static (as in C) so that the array is not destroyed at the output, however this solution is not thread safe. You can also allocate vectors in main and move to their function.

    
19.04.2018 / 02:00