Home > front end >  Segmentation fault(code dumped) in c after several try I cann't get the solution
Segmentation fault(code dumped) in c after several try I cann't get the solution

Time:12-22

#include <iostream>
using namespace std;

int main() {
    int T,D;
    long long int N;
    long long int a[N];
    long long int b[D];
    cin>>T;
    for(int i=0;i<T;i  )
    {
       cin>>N>>D;
        for(int i=0;i<N;i  )
        {
            cin>>a[i];
        }
        for(int i=0;i<D;i  )
        {
            b[i]=a[i];
        }
        for(int i=0;i<(N-D);i  )
        {
            a[i]=a[i D];
        }
        for(int i=0;i<D;i  )
        {
            a[i N]=b[i];
        }
        for(int i=0;i<N;i  )
        {
            cout<<a[i];
        }        
             cout <<endl;
    }
    

    
    return 0;
}

Why is this coding having segmentation fault? I have seen many solution but cann't get it right.On visual studio or any other application it is not working but on gfg it is working. Please help me solve this problem

CodePudding user response:

There are several things that are wrong.

C-style arrays must be set at compile time. So if you want to use int a[N], N must to known at compile time. If you want a flexible array, one C way is to use std::vector.

Then the array a goes from 0 to N-1. So going a[N] is going too far. So a[i N] is way out if bounds and will be segfault.

CodePudding user response:

you declare array a with N element, but use index out of the array range.

long long int a[N]; // declare here, maximum element is N
for(int i=0;i<D;i  )
{
    a[i N]=b[i];    // use index out of array a
}
  •  Tags:  
  • c
  • Related