简体   繁体   中英

Error shows as “Expression must have a const value” when integer variable is used for declaring array size in c++

Hi i have below code ,

# include <iostream>
# include <limits>

using namespace std;

int main()
{
    int runs,innings,timesnotout,n;
    cout<<"Enter the number of players:";
    cin>>n;
    const char name[n][10]; //here error shows as "Expression must have a  constant value" is displayed


}

i am trying to get n value from input and then using the n value as array size

This means exactly what the error message says. You may only use constant expressions declaring arrays. In your case it would be better to use either std::vector<std::string> or even std::vector<std::array<char, 10>>` or to allocate the array in the heap.

If you intend to keep the statistics per player, you should define a struct/class and a vector of such:

struct PlayerStats
{
    std::string Name;
    unsigned int Runs;
    unsigned int Innings;
    unsigned int TimesNotOut;
};

int main()
{
    unsigned int n = 0;
    std::cout << "Enter number of players:  ";
    std::cin >> n; // some error checking should be added
    std::vector<PlayerStats> players(n);
    // ... etc
    return 0;
}

When you want to store something without knowing beforehand the size, you can use a vector. Because it can grow dynamically during the execution of your program.

In your case, you can use something like:

#include <iostream>
#include <vector>

using namespace std;

int main() {

   std::vector<string> nameVec;

   nameVec.push_back("John");
   nameVec.push_back("Kurt");
   nameVec.push_back("Brad");
   //Warning: Sometimes is better to use iterators, because they are more general
   for(int p=0; p < nameVec.size(); p++) {
     std::cout << nameVec.at(p) << "\n";
   }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM