数组声明的编译器错误?

时间:2014-01-16 21:06:54

标签: c++

如何修复这三个错误?

  • 错误C2057:预期的常量表达
  • 错误C2466:无法分配常量大小为0的数组
  • 错误C2133:'randomTickets':未知大小

有问题并且不喜欢[门票]

的线路
int randomTickets[tickets][SIZE];

//global constants
const int SIZE = 6;                     //This is the number of balls per ticket
const int MAX_WHITE = 58;               //This is the range of the white balls
const int MAX_RED = 34;                 //This is the range of the red balls
const int waysToWin = 9;
int* newAr = new int[SIZE];

int main(int argc, const char * argv[])
{
    int tickets = displayMenu();        //Welcome screen lets you buy tickets
    int spending = tickets * 2;         //Charges you for the tickets
    int randomTickets[tickets][SIZE];
//code

提前感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

  

错误C2057:预期的常量表达式

您无法像这样声明randomTickets因为需要在编译时知道数组的维度。 tickets不是编译时常量,因此您有错误。考虑使用std::vector<T>

std::vector<std::vector<int>> randomTickets(tickets, std::vector<int>(SIZE));

或者,您可以嵌套std::array,因为SIZE是常量且在编译时已知:

std::vector<std::array<int, SIZE>> randomTickets(tickets);

通过修复此错误可解决其他错误。

答案 1 :(得分:0)

变量tickets不是常量表达式,这就是原因。

按如下方式更改int randomTickets[tickets][SIZE]

Array* randomTickets = new Array[tickets];

在函数main之外,声明以下类型:

typedef int Array[SIZE];

从这一点开始,您可以将变量randomTickets用作“普通”二维数组,只需在完成后忘记delete[] randomTickets ...