如何使用变量设置数组大小? C ++

时间:2017-10-03 20:46:34

标签: c++

我有一些代码定义了一个名为' size'的变量。然后使用它但由于某种原因它不起作用;错误是"表达式没有评估为常数"

int main()
{
    int size;
    int userValue;
    char input;

    do
    {

        cout << "Enter an int for the size of the array:" << endl;
        cin >> size;

        int a[size];

        cout << "Enter an integer between 1 and " << size << " to search for in the array." << endl;
        cin >> userValue;

        populateArray(a, size);

        linearSearch(a, size, userValue);
        binarySearch(a, size, userValue);

        cout << "Press 'y' and enter to run again or just enter to quit";
        cin.sync();
        cin.get(input);

    }while(input == 'y');
}

您可以忽略其他功能,因为在定义数组之前没有调用它们,我已经尝试将大小设置为某个值,但仍然无效。

编辑:忘了提及

#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;

1 个答案:

答案 0 :(得分:-1)

为什么不使用矢量?

std::vector<int> a(size);

同样在C ++中,您无法使用类似的变量定义数组。

替代:

int* a = new int[size];
// Do stuff
delete [] a;