简体   繁体   English

简单插入排序中的分段错误?

[英]Segmentation fault in a simple insertion sort?

Why this code waits for user to input 10 integers when size of array input by user is 8 ?当用户输入的数组大小为 8 时,为什么此代码等待用户输入 10 个整数? It gives segmentation fault when 10 integers are used.`当使用 10 个整数时,它会出现分段错误。`

#include <iostream>
using namespace std;
int main()
{
    int x, a[x];
    cout << "enter the size of array" << endl;
    cin >> x;
    cout << "enter the elements" << endl;
    for (int j = 0; j < x; j++)
        cin >> a[j];
    for (int i = 1; i < x; i++) {
        for (int k = 0; k < i; k++) {
            if (a[i] < a[k])
                swap(a[i], a[k]);
            else
                continue;
        }
    }
    for (int m = 0; m < x; m++)
        cout << a[m];
}

The issue is in these lines:问题出在这些行中:

int x, a[x];
cout<<"enter the size of array"<<endl;
cin>>x;

Here, when you declare the array a , it sizes it using the value stored in x .在这里,当您声明数组a ,它使用存储在x的值来调整它的大小。 However, at this point, you haven't given x a value, so you get an array of garbage size.但是,此时,您还没有给x一个值,因此您得到了一个垃圾大小的数组。 Reading in x later on doesn't retroactively resize the array (the same way that changing a variable at one point doesn't retroactively change other variables whose value is based on it), so the array size doesn't match the read value.稍后在x读取不会追溯调整数组的大小(与在某一点更改变量不会追溯更改其值基于它的其他变量的方式相同),因此数组大小与读取值不匹配。 Plus, if the array is too big, you might get a stack overflow before you even get to the spot where you read things!另外,如果数组太大,您甚至可能在到达读取内容的位置之前就发生堆栈溢出!

To fix this, consider using something like std::vector rather than raw arrays.要解决这个问题,请考虑使用std::vector类的东西,而不是原始数组。 (As a note, variable-length arrays aren't supported in C++, so using std::vector would be more portable.) (请注意,C++ 不支持可变长度数组,因此使用std::vector会更便于移植。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM