Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 27th, 2012  |  syntax: None  |  size: 0.72 KB  |  hits: 9  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Why does a negative value give segmentation fault for the program which is to find pairs of value from the array which has the given sum?
  2. #include <stdio.h>
  3.  
  4. void findpairs(int arr[], int arr_size, int sum)
  5. {
  6.   int i, temp;
  7.   int hash[100] = {0};
  8.  
  9.   for(i = 0; i < arr_size; i++)
  10.   {
  11.     temp = sum - arr[i];
  12.     if(hash[temp] == 1)
  13.     {
  14.       printf("Pair with given sum %d is (%d, %d) n", sum, arr[i], temp);
  15.     }
  16.     hash[arr[i]] = 1;
  17.   }
  18. }
  19.  
  20. int main()
  21. {
  22.     int A[] = {4,-4,9,2,1,6,5,11};
  23.     int sum =7;
  24.     int arr_size = 8;
  25.     findpairs(A, arr_size, sum);
  26.     return 0;
  27. }
  28.        
  29. hash[arr[i]] = 1;
  30. ...
  31. hash[-4] = 1;
  32.        
  33. temp = 7 - 9;
  34. if (hash[temp] == 1)
  35.        
  36. temp = sum - arr[i];
  37. if(hash[temp] == 1)
  38.        
  39. hash[arr[i]] = 1;