Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

why I am getting segmentation fault (core dumped)

+3 votes
asked Sep 7, 2020 by Pavithra Chandrasekar (150 points)
#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;

 }

1 Answer

0 votes
answered Sep 10, 2020 by Peter Minarik (15,580 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.

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...