【问题标题】:why my selection sort is giving segmentation fault? [closed]为什么我的选择排序会出现分段错误? [关闭]
【发布时间】:2021-03-30 12:31:22
【问题描述】:

请帮助任何人指出代码有什么问题

#include <iostream>
using namespace std;

int main() {
    int n;
    cout << "enter the size of array ";
    cin >> n;
    int arr[n];
    cout << "enter numbers  \n";
    for (int i = 0; i < n; i++) {
        cin >> arr[i];
    }

    for (int i = 0; i < n - 1; i++) {
        for (int j = i + 1; i < n; j++) {
            if (arr[j] < arr[i]) {
                int temp = arr[j];
                arr[j] = arr[i];
                arr[i] = temp;
            }
        }
    }

    cout << "the numbers are\n" << endl;
    for (int j = 0; j < n; j++) {
        cout << arr[j] << " " << endl;
    }

    return 0;
}

我的问题是为什么这段代码没有对数组进行排序,也没有在输入后给出输出,它也显示分段错误?

【问题讨论】:

  • 你试过用调试器运行它吗?你会看到故障发生在哪里。

标签: c++ segmentation-fault output selection-sort


【解决方案1】:

关闭看看这个for循环

for(int j=i+1;i<n;j++)

这是一个简单的错字。

我建议在您的代码中添加一些空格,这样更容易阅读和发现此类错误

for (int j = i + 1; i < n; j++)

更好?

【讨论】:

    猜你喜欢
    • 2021-01-11
    • 1970-01-01
    • 2021-07-30
    • 2018-01-07
    • 1970-01-01
    • 1970-01-01
    • 2011-04-23
    相关资源
    最近更新 更多