动态数组崩溃超过8个元素

1 c c++ arrays crash dynamic

#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";
    }
}
Run Code Online (Sandbox Code Playgroud)

我是编程新手.它崩溃超过8个元素,如果n> 8崩溃..但对于n <8工作正常..不知道为什么!

Hum*_*awi 5

这是问题所在:

 int n, x[n]; // It is undefined behaviour
 cout << "Please enter the number of elements in the array: " << endl;
 cin >> n;
Run Code Online (Sandbox Code Playgroud)

正确的方法是(在你的编译器上使用variable-size-array扩展):

 int n;
 cout << "Please enter the number of elements in the array: " << endl;
 cin >> n;
 int x[n];
Run Code Online (Sandbox Code Playgroud)

使用C++的正确方法是使用std::vector:

 int n;
 cout << "Please enter the number of elements in the array: " << endl;
 cin >> n;
 std::vector<int> x(n);
Run Code Online (Sandbox Code Playgroud)

你必须做一些其他改变才能适应std::vector.