I was trying to sort an array on my own without copying any pre-tought method in my terminal the code gets compiled but I guess it keeps on running in the online compiler it shows segmentation fault.
#include <stdio.h>
int main(){
int arr[]={2,45,23,12,34,6,23,78,9,33}; //minimum of an array
int len=sizeof(arr)/sizeof(int);
//printf("%d\n",len);
int min;
min=arr[0];
int temp;
for(int j=0;j<len;j++){
for(int i=0;i<len;i++){
if(arr[i]<min){
min=arr[i];
temp=i;
}
}
int v;
v=arr[j];
arr[j]=min;
arr[temp]=v;
}
printf("%d\n",min);
for(int k=0;k<len;k++){
printf("sorted array is %d\n",arr[k]);
}
return 0;
}
As
Johhny Moppmentioned in the comment, thetemp=iassignment may not execute. In fact, in your code, it never reaches because you have setmin=arr[0]which is always the minimum=2andif(arr[i]<min)never passes. In your case,tempremains uninitialized. Try putting minimum value at another index in array and your code should assigntemp=i.Now the question is - What happens with uninitialized variable
temp?It's possible that
online compileris settingtempto a value that makesarr[temp]=van illegal read fromout of boundindextempresulting intosegfault.If you tried another compiler, it might not segfault e.g.
Apple clangon mymacOSsetstemp=0at assignment and your code never fails.By the way, your code needs correction for sorting the array. There are better ways, so I will leave up to you to figure out the changes :).
Here is the updated code with minimal changes: