#include <vector>
#include <sstream>
#include <fstream>
#include <iostream>
usingnamespace std;
int main()
{
//open file
ifstream myfile;
myfile.open("proj2.txt");
if(myfile.fail())
{
cout << "Unable to open file";
exit(1); //exit program
}//end if
int num = 0; //initialize number
//declare vector
vector<int> vec;
while(myfile >> num)
{
//append number to the vector
vec.push_back(num);
}//end while
//declare array with size of the vector
int *arr = newint[(vec.size()-1)]; //must be declared on the heap for we don't know the size
//load array with data from text file
for(int i = 0; i < vec.size(); i++) //problem is in here somewhere
{
arr[i] = vec[i]; //put the i'th value of the vector into the i'th value of the array
}//end for
myfile.close();
delete [] arr; //where the error comes in
return 0;
}//end main
I was able to isolate the problem to the loop I placed a comment at. If I comment that part out it works. Also, if I leave the last element empty in the array it works. Not sure what's going on here. Any help would be greatly appreciated.
There is no error code, it compiles fine, but crashes when I delete arr off the heap.
n = n - 1; // compensate for the index starting at 0
vec.erase(vec.begin() + n);
//delete array element
//first shift everything accordingly
//start at i = n, and then end at vector length
for(unsignedint i = n; i < vec.size(); i++)
{
arr[i] = arr[i+1];
}//end for
//save the address of the memory arr is refrencing
int* savedAddy = arr;
//allocate some memory for an array with size (n-1)
arr = newint[vec.size()-1]; //the size has been decreased by 1
//copy the contents to the new array
for(unsignedint i = 0; i < vec.size()-1; i++)
{
arr[i] = savedAddy[i];
}//end for
delete [] savedAddy;