[英]Segmentation fault in a simple insertion sort?
當用戶輸入的數組大小為 8 時,為什么此代碼等待用戶輸入 10 個整數? 當使用 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];
}
問題出在這些行中:
int x, a[x];
cout<<"enter the size of array"<<endl;
cin>>x;
在這里,當您聲明數組a
,它使用存儲在x
的值來調整它的大小。 但是,此時,您還沒有給x
一個值,因此您得到了一個垃圾大小的數組。 稍后在x
讀取不會追溯調整數組的大小(與在某一點更改變量不會追溯更改其值基於它的其他變量的方式相同),因此數組大小與讀取值不匹配。 另外,如果數組太大,您甚至可能在到達讀取內容的位置之前就發生堆棧溢出!
要解決這個問題,請考慮使用std::vector
類的東西,而不是原始數組。 (請注意,C++ 不支持可變長度數組,因此使用std::vector
會更便於移植。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.