Вращение массива: ошибка сегментации (SIGSEGV) - PullRequest
1 голос
/ 21 июня 2019

Учитывая массив размером N. Задача состоит в том, чтобы повернуть массив на d элементы, где d меньше или равно N.

Ограничения: 1 ≤ T ≤ 200 1 ≤ N ≤ 200 1 ≤ A [i] ≤ 1000

Пример ввода:

1
5
1 2 3 4 5
2

выход

3 4 5 1 2

Программа, которую я написал, кажется законной, но когда я пытался ее запустить, это вызывает ошибку сегмента. Я даже запустил приведенный выше пример, я получаю правильный вывод. Источник: GeeksforGeeks: Вращающийся и Массив .

#include <bits/stdc++.h>
using namespace std;

int main() {
  int test_case, numb, from, arr[200];

  cin >> test_case;
  while (test_case--) {
    cin >> numb;

    for (int i = 0; i < numb; i++) {
      cin >> arr[i];
    }

    cin >> from;
    for (int i = from; i < numb; i++) {
      cout << arr[i] << " ";
    }
    for (int j = 0; j < from; j++) {
      cout << arr[j] << " ";
    }

    cout << "\n";
  }
  return 0;
}

Какие изменения нужны моему коду? Что я могу сделать, чтобы избежать таких ошибок в будущем? click_to_see_segment_fault

Ответы [ 3 ]

1 голос
/ 21 июня 2019

enter image description here Только что отправили свой точный код на Вращение массива |Компьютерщик для Компьютерщиков (сайт указан в вопросе).Он работает отлично, и не было обнаружено ни одной ошибки во время выполнения.

0 голосов
/ 21 июня 2019

Запустите следующий ввод и увидите странные результаты.Проблема в том, что from больше, чем само количество элементов.По сути, вам нужно проверить, больше ли число элементов from превышает число элементов numb.

#include <bits/stdc++.h>
using namespace std;

int main() {
  int test_case, numb, from, arr[200];
  cout<<"\nEnter number of test cases:";
  cin >> test_case;
  cout<<"Test cases = "<<test_case<<endl;
  while (test_case--) {
    cout<<"Enter count of elements:";
    cin >> numb;
  cout<<"Count= "<<numb<<endl;

cout<<"Enter the elements:";
    for (int i = 0; i < numb; i++) {
      cin >> arr[i];
    }
cout<<"Entered elements are :";
    for (int i = 0; i < numb; i++) {
      cout << arr[i]<<" ";
    }

cout<<"\nHow many times to rotated? :";
    cin >> from;
cout<<"\nRotate it "<<from<<" times:\n";
    for (int i = from; i < numb; i++) {
      cout << arr[i] << " ";
    }
    for (int j = 0; j < from; j++) {
      cout << arr[j] << " ";
    }

    cout << "\n";
  }
  return 0;
}

. Позволяет ввести следующие данные:

Enter number of test cases:1
Test cases = 1
Enter count of elements:1
Count= 1
Enter the elements:2
Entered elements are :2
How many times to rotated? :2

Rotate it 2 times:
2 32666

Вы видите ошибку?Местоположение, где 32666 является проблемой здесь.Это может привести к сбою в вашем случае.

0 голосов
/ 21 июня 2019
#include <bits/stdc++.h>
using namespace std;

int main() {
    int test_case, numb, from, arr[200];
    cout<< "Enter the numbe of test cases"<<endl;
    cin >> test_case;
    if(test_case > 200)
    {
            cout<<"Number of test cases above limit";
            return 0;
    }
    while (test_case--) {
            cout<<"START TEST CASE"<<test_case<<endl;
            cout<<"Enter the number of elements in the array"<<endl;
            cin >> numb;
            if(numb > 200)
            {
                    cout<<"Array size more than expected skipping testcase"<<endl;
                    continue;
            }
            cout<<"Enter the elements of array"<<endl;
            for (int i = 0; i < numb; i++) {
                    cin >> arr[i];
            }
            cout<<"Enter the number of rotations"<<endl;
            cin >> from;
            if(from > numb || from < 0)
            {
                    cout <<"rotation index out of range skipping testcase"<<endl;
                    continue;
            }
            for (int i = from; i < numb; i++) {
                    cout << arr[i] << " ";
            }
            for (int j = 0; j < from; j++) {
                    cout << arr[j] << " ";
            }

            cout << "\n";
    }
    return 0;
}

Расширяя ответ Чарли, Программа проверяет диапазоны numbs и диапазон.

...