When I try to convert a vector of integers to a array of integers inside a loop although within the loop the conversion appears to have worked, once the loop terminates the value within the array is incorrect.
I tried using std::copy instead of &vector[0], and the same problem arose. I am aware that converting the vector to an array is not necessary. I assume the problem is that the array is a pointer to a variable that is destroyed after the loop, but I'm fairly new to C++, so even if I am correct, I don't know how to fix it.
#include "pch.h"
#include <iostream>
#include <vector>
int main()
{
int* arr;
for (int i = 0; i < 1; i++)
{
std::vector<int> vec{ 1 };
arr = &vec[0];
std::cout << "Inside the loop in the vector: " << vec[0] << std::endl;
std::cout << "Inside the loop in the array: " << arr[0] << std::endl;
}
std::cout << "Outside the loop in the array: " << arr[0];
}
I would expect the output to look like this:
Inside the loop in the vector: 1
Inside the loop in the array: 1
Outside the loop in the array: 1
But it actually turns out like this:
Inside the loop in the vector: 1
Inside the loop in the array: 1
Outside the loop in the array: -572662307