Home > Blockchain >  for this code I am getting run time error .Abort signal from abort(3) (SIGABRT)'
for this code I am getting run time error .Abort signal from abort(3) (SIGABRT)'

Time:10-05

 #include <iostream>
using namespace std;
void reverse(int A[],int N){
    
    for(int i=0;i<N/2;i  ){
        swap(A[i],A[N-i-1]);
    }
        for(int i=0;i<N;i  ){
        cout<<A[i];
    }
}

int main() {
    //code
    int T,N,A[N];
    cin>>T>>N;
    for(int i=0;i<N;i  ){
        cin>>A[i];
    }
    reverse(A,N);
    //please help it its getting into my nerves

    return 0;
}

please help me resolve this problem for this code I am getting run time error .Abort signal from abort(3) (SIGABRT)'

CodePudding user response:

You are getting error because you didn't initialize your variables with default values.

Problem 1: int T,N,A[N]; here N is initialized with garbage value.

Problem 2: you initialize / declare A[] before getting N value from the input.

Solution :

 int T,N;
 cin>>T>>N;
 int A[N];

Side note: There is better and efficient solution using vector given below :

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

void reverse(vector<int>& x) {
     reverse(x.begin(), x.end());

  return;
}

int main() 
{
vector<int> list;
int listSize;

cout << "How much element you want to put in list" << endl;
cin >> listSize;

cout << "Enter the numbers :" << endl;
for (int number; cin >> number;) {
        list.push_back(number);
     
     if (list.size() == listSize)
        break;

}

reverse(list);

cout << "The reverse of your numbers : ";
for (const int x : list)
    cout << x <<' ';

cout << endl;

return 0;

}

CodePudding user response:

Here the problem is that you are declaring A[N] before any value has been assigned to N. Declare A[N] once you have input the value of N.

  • Related