I'm trying to add an int array into a vector. No matter what I do, the debugger indicates the new vector element is simply "0".
std::vector< int * > level_collection;
for( auto & i : levels )
{
auto size = std::get< 1 >(i).size();
int level_data[size];
for( size_t x = 0; x < size; x ++ )
{
level_data[x] = std::get< 1 >(i)[x];
}
for( auto x : level_data)
{
std::cout << x << std::endl; // This works. All the values print correctly. So it did store the information as it should.
}
level_collection.push_back( level_data );
}
for( auto & i : level_collection)
{
std::cout << i[1] << std::endl; // This prints ALL 0s. Despite the new element not having that value.
}
I've been looking hours for a solution. I can't seem to find any.
What I've tried:
- Changing the location of level_data so it's not always reinitialized every time.
- Removing level_data and instead adding a new element to level_collection and copying the values returned in std::get directly into the vector
- Checked through the debugger and output that level_data does indeed return the correct array with the correct values. However, the moment it's added to level_collection, it turns to 0. (Doesn't matter if I try the other things I mentioned above)
I'm sure there's an easy solution here. I might just be overlooking something.
Edit: I unfortunately cannot use std::array in this assignment. We were told to work off of what's available. The function level_collection gets passed to is a "const int *"
level_datatolevel_collection?sizea constant expression? If not,int level_data[size];is not standard C++. Also,level_data's "pointer" you put in the vector is invalid outside the scope in whichlevel_datais declared.v_levels_output?std::array. Each array, that youpush_backed gets destroyed at the end of each loop iteration. Hence, each pointer is a dangling pointer, dereferencing which, leads to undefined behavior.