#include<iostream>
using namespace std;
void arrayin(int x[], int n);
void arrayout(int x[], int n);
main()
{
int n, x[n];
cout << "Please enter the number of elements in the array: " << endl;
cin >> n;
cout << "Please enter the elements: " << endl;
arrayin(x,n);
cout << "Array is of " << n << " elements."<< endl;
cout << "Elements are as follow :" << endl;
arrayout(x,n);
}
void arrayin(int x[],int n)
{
for (int i = 0; i < n; i ++)
{
cin >> x[i];
}
}
void arrayout(int x[], int n)
{
for (int i = 0; i < n; i++)
{
cout << x[i] << "\t";
}
}
我是编程新手。 它崩溃超过 8 个元素,如果 n > 8 崩溃..但对于 n<8 工作正常.. 不知道为什么!
最佳答案
问题是:
int n, x[n]; // It is undefined behaviour
cout << "Please enter the number of elements in the array: " << endl;
cin >> n;
正确的方法是(在带有可变大小数组扩展的编译器上):
int n;
cout << "Please enter the number of elements in the array: " << endl;
cin >> n;
int x[n];
使用 C++ 的正确方法是使用 std::vector
代替:
int n;
cout << "Please enter the number of elements in the array: " << endl;
cin >> n;
std::vector<int> x(n);
并且您必须进行一些其他更改以适应 std::vector
。
关于c++ - 超过 8 个元素的动态数组崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41141036/