A constant value is expected when initialize an array
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 erro开发者_高级运维r 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}
};
In the delclaration your are adding the elements, so you don't need to specify the size.
So this will work :
int[,] kernel = new int[,] {
{1, 2, 1},
{2, 4, 2},
{1, 2, 1}
};
精彩评论