I have a class which defines few global variables as below:
namespace Algo
{
public static class AlgorithmParameters
{
public int pop_size = 100;
}
}
In my another csharp file, which also contains the main(), and in the main() I am declaring an array of type structure and the array size as pop_size but I am getting some error on "chromo_typ Population[AlgorithmParameters.pop_size];". Please find the code below. Am I using a incorrect syntax for array declaration of variable length size??
namespace Algo
{
class Program
{
struct chromo_typ
{
string bits;
float fitness;
chromo_typ() {
bits = "";
fitness = 0.0f;
}
chromo_typ(string bts, float ftns)
{
bits = bts;
fitness = ftns;
}
};
static void Main(string[] args)
{
while (true)
{
chromo_typ Population[AlgorithmParameters.pop_size];
}
}
}
}
Error is:
Bad array declarator: To declare a managed array the rank specifier precedes the variable's identifier. To declare a fixed size buffer field, use the fixed keyword before the field type.
Array size cannot be specified in a variable declaration (try initializing with a 'new' expression)
Please help.
You don't specify the size when you declare the variable, you specify it when you create the instance of the array:
chromo_typ[] Population = new chromo_typ[AlgorithmParameters.pop_size];
Or if you separate the declaration and creation:
chromo_typ[] Population;
Population = new chromo_typ[AlgorithmParameters.pop_size];
Change the initialize in this way:
//while (true) ///??? what is the reason for this infinite loop ???
//{
chromo_typ[] Population = new chrom_typ[AlgorithmParameters.pop_size] ;
//}
also you need to change pop_size to a static because is declared inside a static class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With