# why I am getting segmentation fault (core dumped)

asked Sep 7, 2020
#include<iostream> using namespace std;

template<typename T>

class sort

{

private:

T i,temp;

public:

sort(T n,T a[]);

};

template<typename T> sort<T>::sort(T n,T a[])

{

for(i=0;i<n;i++)

{

if(a[i]>a[i+1])

{

temp=a[i];

a[i]=a[i+1];

a[i+1]=temp;

}

}

cout<<"After sorting the elements are:";

for(i=0;i<n;i++)

{

cout<<a[i];

}

}

int main()

{

int n,i,a[n];

cout<<"Enter the number of elements to be sorted:"<<endl;

cin>>n;

cout<<"Enter the elements one by one:"<<endl;

for(i=0;i<n;i++)

{

cin>>a[i];

}

sort<int>ob(n,a);

return 0;

}

answered Sep 10, 2020 by (58,190 points)
edited Sep 11, 2020 by Peter Minarik

This is, because you initialise the array a with the size n in the first line of main(). At this point, n is not set, its value is indeterminate. Hence the segmentation fault.

So declare your array a, after the value n is read.

Now, your code will run.

Unfortunately, the sorting does not work correctly, so you need to fix that too.

Have a look at this for various sorting algorithms: https://www.geeksforgeeks.org/sorting-algorithms/

I'd focus on the Bubble Sorting, as it's easy to understand. It's not too effective, but you should have a working code first and worry about efficiency later.

If you fancy a better sorting that's a bit harder to understand, look at the Quick Sort algorithm.