I am making a c++ program which should read in from standard input an integer N. It should then read from a file “data.txt” values into an array of size N. then it should pass it to a function which reverses the array and returns a pointer to the new array. Then it should print the contents of the returned pointer’s array. But everytime I run the program it crashes. Any ideas?
#include <iostream>
#include <fstream>
using namespace std;
int * reverseArray(int * arr, const int size)
{
//int arr1[size];
int *arr2 = new int[size];
for(int iii = 0; iii < size; iii++)
{
(*(arr2+iii)) = (*(arr + size - 1 - iii));
}
return arr2;
}
int main()
{
int N;
cin >> N;
if(N >= 0 && N <= 50)
{
ifstream inputFile;
inputFile.open("data.txt");
int *arr = new int[N];
int iii = 0;
while(inputFile >> (*(arr+iii)) && iii < N)
{ iii++;}
arr = reverseArray(arr, N);
for(int jjj = 0; jjj < N; jjj++)
{
cout << (*(arr+jjj)) << endl;
}
delete [] arr;
inputFile.close();
}
return 0;
}
I think the problem is here:
The check to ensure
iiiis less thanNoccurs after the access. Reorder the conditions:Note this line introduces a memory leak:
As this is C++ consider using
std::vector<int>instead.