Why this question is not duplicate?
The problem can't be at scanf, as it is given by the hackerrank and I can't modify the code! Also, test cases are automated, given by hackerrank. We can trust them with input reading. There is some bug in my logic of finding two elements in array, couldn't find it though :|
Note: I can't modify main method, as mentioned earlier. Re-iterating it. Why can't I modify? It is because the method is given by the portal. I can't change it. It reads the input and calls my method through some automated scripts, I've no control over it. So, please don't tell me to modify main method.
I was trying some practice problems in hackerrank in C language and some of the test cases started throwing Segmentation fault for following problem. I've tried understanding it for more than 2 hours now and couldn't think of any test case which will throw segmentation fault. I'm stuck :|
Problem statement:
Given an array and a number. Find if there are 2 elements in array, whose sum is equal to given number. If number are present return 1, otherwise 0.
pretty easy, huh? I thought the same and coded it as follows,
int compFunc (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int isSumPossible(int a[], int L, int N ){
/*L: Length of the array */
if(a==NULL) return 0;
if(L<=1) return 0;
int left=0, right=L-1;
qsort(a,L,sizeof(int),compFunc);
while(left<right)
{
if(a[left]+a[right]==N) return 1;
else if(a[left]+a[right]<N) left++;
else right--;
}
return 0;
}
int main() //given by hackerrank, I can't modify main method
{
int N; scanf("%d", &N); //fixed &N - it was correctly given in code, I missed it while typing it here.
int a[100004], i=0;
//read input into array a, based on N
int x;scanf("%d", &x); //fixed &x - it was correctly given in code, I missed it while typing it here.
printf("%d", isSumPossible(a,N,x));
}
Please assume all the header files required are included. Now, when I ran the code, most of the test cases passed and for some test cases they showed Segmentation fault. Unfortunately test cases aren't visible to me :|. I've gone through my code more than 10 times & I don't understand in which scenario I would get Segmentaion fault. Can anyone help me in understand which scenario am I missing in my code and why do I see segmentation fault?
if(a[left] + a[right] == N)- Almoscanfneeds address arguments to store the parsed values. i.e.scanf("%d",&N);,scanf("%d",&x);. - Jean-Baptiste YunèsNandxin the program source won't be much help, as those names have no meaning.printf("Enter the (whatever)\n");- Weather Vane