'segmentation fault'

There are no errors when I compile my program but when i try to run this it says segmentation fault

I am a beginner and we just learned files so i am clueless

#include <iostream>
#include <fstream>
#include <ostream>
#include <cstdlib>
using namespace std;

int main()
{
ifstream infile;
int n, median, arr[n], i=0;

infile.open("data7.txt");
if (infile.fail())
{
cout << "Input file opening failed.\n";
exit(1);
}

while (infile >> n)
{
arr[i] = n;
i++;
}

if ((i+1)%2==1)
cout << arr[(i+1)/2];
else
cout << (arr[i/2] + arr[(i+1)/2])/2;




}

#include <ostream>
This is pretty unnecessary.

int n, median, arr[n], i=0;
Even if your compiler allows it, variable sized, static arrays are not legal (at least until C++14). These arrays must have a known, constant size at compile time.
1
2
const unsigned arr_size = 50;
int arr[arr_size];


The segmentation fault is most likely happening because you are going out-of-bounds of your array. When you start reading from the file and inserting the items into your array, there are two issues:
1) n has never been initialized. You don't know the size of your array.
2) You do not check if you reach the size limit of your array. This will allow the program to attempt writing data into the wrong place, causing segmentation errors.
Topic archived. No new replies allowed.