在函数调用结束后保持数组的内容.(C++)

phy*_*ael 1 c++ memory arrays

可以说我有以下代码.

double *return_array(void) {
   double foo[2];
   foo[0] = 5;
   foo[1] = 6;
   cout << foo << endl;
   cout << foo[0] << endl << foo[1] << endl;
   return foo;
}

double *bar = return_array()
cout << bar << endl;
cout << bar[0] << endl << bar[1] << endl;
Run Code Online (Sandbox Code Playgroud)

现在,bar和foo仍然是同一个指针,但那里的内容已经完全改变了.我怎么能绕过这个?基本上,我需要从一个函数传递6或9个双打.我该怎么办?

Ara*_*raK 5

使用矢量.

std::vector<double> return_array(void) {
   std::vector<double> foo;
   foo.push_back(5);
   foo.push_back(6);
   cout << foo[0] << endl << foo[1] << endl;
   return foo;
}
Run Code Online (Sandbox Code Playgroud)

这是一种更好的方法,所以你避免复制矢量:

void fillVector(std::vector<double>& vec)
{
    vec.push_back(5);
    vec.push_back(6);
}

int main()
{
    std::vector<double> vec;

    fillVector(vec);
}
Run Code Online (Sandbox Code Playgroud)

现在,bar和foo仍然是同一个指针,但那里的内容已经完全改变了.

因为foo在函数的堆栈上分配,所以当函数返回时它会被释放.所以,bar实际上是指向哪里!