c++ - What is cause of segmentation fault here? -
i have written small array merge procedure. on running getting segmentation fault. can point out me have gone wrong here?
#include <iostream> using namespace std; void merge(int arr[], int p, int q, int r) { int l[q-p+1]; int r[r-q]; for(int = p; < r;i++) { if(i<q+1) { l[i] = arr[i]; } else { r[i-q+1] = arr[i]; } } int = 0, j = 0,k = p; while(i<q-p+1 || j<r-q) { if(l[i]>r[j]) { arr[k] = r[j]; j++; } else { arr[k] = l[i]; i++; } k++; } if(i == q-p+1) { for(;j<r-q;j++,k++) { arr[k] = r[j]; } } if(j == r-q) { for(;i<q-p+1;i++,k++) { arr[k] = l[i]; } } } int main() { cout << "hello world!" << endl; int a[] = {2,4,6,8,1,3,5,9}; merge(a,0,3,7); for(int = 0; i<8;i++) { cout<<a[i]<<"\t"; } return 0; }
you should step through in debugger.
this line of code:
while (i<q - p + 1 || j<r - q)
will not prevent being >= q-p+1
(i.e if j still less r-q
). mean reading outside of array boundaries.
you should change to
while (i<q - p + 1 && j<r - q)
also note: int l[q-p+1]
not valid c++, valid c, not c++
Comments
Post a Comment