Could you please tell me what is the issue with my code? I am getting segmentation fault for this specific input (and more) but for few it running fine?
What is it that I am missing?
void sortArr(int a[], int n)
{
int x,y;
for(int i=0;i<n;i )
{
if(a[i]==0)
{
x ;
}
else if(a[i]==1)
{
y ;
}
}
int i;
for(i=0;i<x;i )
{
a[i]=0;
}
for(i=x;i<(x y);i )
{
a[i]=1;
}
for(i=(x y);i<n;i )
{
a[i]=2;
}
// Print the sorted array
printArr(a, n);
}
// Driver code
int main()
{
int arr[] = {0,2,1,2,0,2,2,0,0,1};
int n = sizeof(arr) / sizeof(int);
sortArr(arr, n);
return 0;
}
CodePudding user response:
Initialize your variables before using them:
int x = 0, y = 0;
If you don't initialize the variables, then they will have indeterminate values which may lead to undefined behavior, and in some cases, this can also cause errors. (For example with MSVC)