I have a piece of code:
int CPUs = GetNumCPUs();
FILE *newFile[CPUs];
I got an error. It marks 'CPUs' on the second line and says: "expression must have a constant value".
I have tried to use const but it is not working.
In your code, const doesn't mean "constant". In this context, it means the object is read-only — i.e you can't modify the object. You're trying to create a variable length array, which isn't allowed in C++. Use std::vector, use new to allocate memory, or write a C99 program where VLAs like the one you're trying to make are allowed.
new to allocate memory isn't really an option.const doesn't mean constant.Using a const doesn't fix all of your problems in this scenario. The problem is that arrays must be initialized at compile time, so if you have a function return a variable (GetNumCPUs()) and assign it to a constant (const int CPUs), the variable isn't known at compile time but runtime, and the compiler can't allocate data space for the array.
Using an std::vector, however, allows for variable storage space.
std::vector<FILE*> newFile(CPUs);
This should work fine. Here's a couple tutorials:
http://www.dreamincode.net/forums/topic/33631-c-vector-tutorial/
You should dynamically create the array with new[]
int CPUs = GetNumCPUs();
FILE** newFile = new (FILE*)[CPUs];
After you're done with it, you're now responsible for deleting it as well:
delete[] newFile;
std::vector<> without an explanation / justification.
FILE **newFile = new FILE*[CPUs];, or better, use astd::vector.std::vector.