Consider the following simple example:
#include <vector>
void func(std::vector<int>* output) {
std::vector<int> temp(10000);
/* ... do work here and fill temp with useful values ... */
// now send the result to main
*output = temp;
}
int main(void) {
std::vector<int> vec;
// func will put useful values in vec
func(&vec);
for(size_t i=0; i<10000; i++)
vec[i] = 3; // just checking to see if I get a memory error
return 0;
}
I used to think one has to first allocate memory for vec before being able to use it (e.g., by calling output->resize(10000)?). Therefore I expected to get a memory error when using vec after calling func in the for loop, but it seems that the code works just fine.
Can you please explain this behavior? Also, is this how you'd write this code (i.e., when you need a function that is supposed to fill a vector, perhaps each time with a different number of values although here it's 10000)? (PS. I don't want to use return).
Thanks!