I developing an image processing software.
int size = 3;
int[,] kernel = new int[size, size] {
{1, 2, 1},
{2, 4, 2},
{1, 2, 1}
};
When I compile my code, I have a compile error message "A constant value is expected" from size
variable. I understand I can put 3 on my kernel
array initialization or make my size
constant. What I ask is the technical reason behind this error because this error don't make any sense for me.
You can either create an array with empty values by specifying only the size (which may be variable), or list the values in an initializer and optionally specify a constant size. But you can't combine an initializer with a non-constant size. In the case of the initializer you're allowed to specify constant values for the size, if you want to make sure that the initializer results in an array of a specific size.
Just get rid of the size parameters, your initializer list already specifies the size.
The compiler requires a constant expression for the array ranks. You can declare size
as const int
, or you can just let the compiler figure it out from the initialization expression:
int[,] kernel = new int[,] {
{1, 2, 1},
{2, 4, 2},
{1, 2, 1}
};
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