I am trying to solve a problem which is a Basic level Array problem. I implemented my logic and passed the sample test cases given on that page and also tried some custom inputs and it did worked as intended. But when I submit my code it gives a Segmentation Fault, but unfortunately it didn't tell on which particular test case it happens.
So, here is my logic:-
Check if K divides N exactly or not because if it does we can simply use
reverse
function in a loopIf it doesn't we first reverse the elements up to e(which are under the given group)
- Then we reverse the remaining elements separately
Here is my code:-
#include <bits/stdc++.h>
using namespace std;
int main(){
int T; cin >> T;
while(T--) {
int N, K;
cin >> N >> K;
int A[N];
for (int i = 0; i < N; i++)
cin >> A[i];
if (N / K != 0) {
int G = (int)(N / K); // G -> groups
int e = G * K; // e -> no. of elements which fall under given group
for (int i = 0; i < e; i += K)
reverse(A + i, A + i + K);
reverse(A + e , A + N); // reversing remaining elements
}
else {
for (int i = 0; i < N; i += K)
reverse(A + i, A + i + K);
}
for (int i = 0; i < N; i++)
cout << A[i] << " ";
cout << "\n";
}
return 0;
}
Now everything is working as expected but why it is giving SIGSEGV on submitting the code? and how can I find which particular line is causing this?
PS: I know that I shouldn't use using namespace std
and bits/stdc++.h
and I know it's implications