Don't do this:
void getArray(double* a)
{
std::vector<double> v;
a = &v[0];
} // The vector is destroyed here, and the memory
// is deallocated.
In any case, you're not modifying the a
pointer outside of your function, so you won't get the desired effect.
Instead, return the vector
and use it directly. Or, in general, use vectors throughout your code. If you need to pass them in to a function that expects a pointer to an array, you can pass &v[0]
there. Such a function usually expects the size too. For this, pass v.size()
. You can do this safely as long as that function doesn't take ownership, or deallocate the memory.
Note, also, that a vector declared as std::vector<double> v;
does not have a size, so attempting to access the first element, as in v[0]
is also undefined behaviour. At the very least, you need to give the vector a size (pass a size to its constructor) to ensure some memory is allocated. You should always make sure the vector has some allocated memory before indexing into it, including when trying to take the address of the first element.
What you probably want to do is:
std::vector<double> getArray() {
std::vector<double> v = /* some sane initialisation */;
return v;
}
// some time later, assuming a function:
// void do_something(double* a, size_t n);
// ...
std::vector<double> v = getArray();
if (v.size()) {
do_something(&v[0], v.size());
} else {
// fail gracefully
}