I try this simple program:
int* getElement(int arrayy[], int index) {
return &arrayy[index];
}
int main() {
int arrayy[4]{};
*getElement(arrayy, 2)=50;
std::cout << arrayy[2] << '\n';// here it prints 50 !
return 0;
}
getElement()
will return the address of an element of my array through a pointer return, dereference it in the main and then change the value.
I want to do the same thing using std::array
in the place of classic array.
int* getElement(std::array<int, 4> arrayy, int index) {
return &arrayy[index];
}
int main() {
std::array<int, 4> arrayy{};
*getElement(arrayy, 2)=50;
std::cout << arrayy[2] << '\n';//here it prints 0 !
return 0;
}
in the first it prints 50 and in the second 0 !
does std::array
pass by value in calls ?
In the case of passing a pointer by value, the pointed at values are the same in the function and the call site. So the first program does what you expect.
In the second program, it's different because std::array
has value semantics, so passing it by value means that you are passing a copy of all the underlying memory as well.
Note that in your code in the second program, the result of 0
is not guaranteed. You are returning a pointer to a value inside the copied std::array
which will die when the function returns. This invokes undefined behavior.
If you want to get the same effect as the first program, you need to pass the std::array
by reference instead:
int* getElement(std::array<int, 4> &arrayy, int index) {
// ^ reference
return &arrayy[index];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With