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 the std::copy instead of &vector[0] and the same problem arises. And I am aware that converting the vector to a array is not necessary. I assume the problem is due because the array is assigned a pointer to a variable which 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