Unsolved programming error

What is wrong with this c code for countsort.i am getting segmentation fault for no reason.
#include<stdio.h>
void countersort(int a[],int numele,int range);
int main()
{int i,numele,element,range;
int arr[10];
printf(“How many elements do you want to enter \n”);
scanf("%d",&numele);
printf(“Enter the range \n”);
scanf("%d",&range);
for(i=0;i<numele;i++){
scanf("%d",&element);
arr[i]=element;
}
for(i=0;i<numele;i++){
printf("%d",arr[i]);
}

printf(“right till here \n”);
countersort(arr,numele,range);
printf(“right till herr”);
for(i=0;i<numele;i++){
printf("%d \t",arr[i]);
}
printf("\n");
return 0;
}
void countersort(int a[],int numele,int range)
{ printf(“right till here”);
int c[10]={0};
int b[10];
int i;
printf(“right till here”);
// for(i=0;i<10;i++){
// c[i]=0;
// }
printf(“right till here”);
for(i=0;i<numele;i++){
c[a[i]]=c[a[i]]+1;
}
printf(“right till here”);
for(i=1;i<=range;i++){
c[i]=c[i]+c[i-1];
}
for(i=0;i<numele;i–){
b[c[a[i]]]=a[i];
c[a[i]]=c[a[i]]-1;
}
for(i=0;i<numele;i++){
a[i]=b[i];
}

}

Check your for loop construction :

for(i=0;i<numele;i--){
 b[c[a[i]]]=a[i];
 c[a[i]]=c[a[i]]-1;
}

The value of i becomes -1 after the first time loop executes.
This makes the reference a[i] as a[-1] and such a memory reference cannot be made for any array as array indices start with 0.

So, whatever you are doing, you can try this :

for(i=0;i<numele;i++){
 b[c[a[i]]]=a[i];
 c[a[i]]=c[a[i]]-1;
}

or
for(i=numele-1;i>=0;i–){
b[c[a[i]]]=a[i];
c[a[i]]=c[a[i]]-1;
}

However, I recommend using functions like malloc() and calloc() instead of declaring int b[10] and c[10]. There are huge chances of users inputting higher values in int a[].

1 Like
//