c++ - 超过 8 个元素的动态数组崩溃

标签 c++ c arrays dynamic crash

#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/

相关文章:

c - 我正在学习 C 中的指针,并从一个基本概念开始,但我不断收到错误。我究竟做错了什么?

c++ - 将方程的值赋给变量有问题

java - 分配给Java中的字节数组

c++ - QTableView如何获取滚动条所在行的位置

c - 传递数组时在C中的函数参数中强制数组大小

c - 使 fgets() 忽略新行

c++ - VC++ HeapAlloc 内部函数给出空指针

java - 如何使用 Java 将每个文件存储在 zip 存档中的数组中?

c++ - 在声明期间用值初始化类方法的参数 C++

c++ - Qt MacOS - 正确的工作目录?