Compiler error on array declaration?

前端 未结 2 1624
深忆病人
深忆病人 2021-01-28 15:39

How do I go about fixing these three errors?

  • error C2057: expected constant expression
  • error C2466: cannot allocate an array of constant size 0
  • e
相关标签:
2条回答
  • 2021-01-28 16:06

    error C2057: expected constant expression

    You can't declare randomTickets like that because the dimensions of the array need to be known at compile time. tickets is not a compile time constant and therefore you have the error. Consider using std::vector<T>:

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

    Alternatively, you can nest a std::array since SIZE is constant and known at compile time:

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

    The other errors are resolved by fixing this one.

    0 讨论(0)
  • 2021-01-28 16:08

    Variable tickets is not a constant expression, that's why.

    Change int randomTickets[tickets][SIZE] as follows:

    Array* randomTickets = new Array[tickets];
    

    Outside of function main, declare the following type:

    typedef int Array[SIZE];
    

    You can use variable randomTickets as a "normal" 2-dimensional array from this point onwards, just don't forget to delete[] randomTickets when you're done...

    0 讨论(0)
提交回复
热议问题