Revist Revist - 1 year ago 74
C++ Question

Passing pointer to array instead of array

when I have a function that takes an array for example

void foo(std::vector<double> array)

and I first create a pointer to some array

std::vector<double> *array_pointer;

then point it at an array

array_pointer = &array;

and pass it to the function as


do I get the same as if I would pass the array i.e.



Answer Source



void foo(std::vector<double> array)

array is passed by value. foo will make a copy of the passed parameter and operate on the copy. Whatever you do to array in foo will not be observed by the caller because it has a different array.

foo cannot be called with a pointer. Note that you had to dereference the pointer, get the the object pointed at, with *array_pointer to call foo rather than pass the pointer. This has the effect of putting you right back where you started.

If your problem is with the caller not getting an updated array after foo has returned, consider passing array by reference:

void foo(std::vector<double> &array)

Now no copy takes place and foo can directly modify the array provided by the caller.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download