[英]C++ error: “Array must be initialized with a brace enclosed initializer”
I am getting the following C++ error:我收到以下 C++ 错误:
array must be initialized with a brace enclosed initializer
From this line of C++从这行 C++
int cipher[Array_size][Array_size] = 0;
What is the problem here?这里有什么问题? What does the error mean?错误是什么意思? Below is the full code:下面是完整的代码:
string decryption(string todecrypt)
{
int cipher[Array_size][Array_size] = 0;
string ciphercode = todecrypt.substr(0,3);
todecrypt.erase(0,3);
decodecipher(ciphercode,cipher);
string decrypted = "";
while(todecrypt.length()>0)
{
string unit_decrypt = todecrypt.substr(0,Array_size);
todecrypt.erase(0,Array_size);
int tomultiply[Array_size]=0;
for(int i = 0; i < Array_size; i++)
{
tomultiply[i] = int(unit_encrypt.substr(0,1));
unit_encrypt.erase(0,1);
}
for(int i = 0; i < Array_size; i++)
{
int resultchar = 0;
for(int j = 0; j<Array_size; j++)
{
resultchar += tomultiply[j]*cipher[i][j];
}
decrypted += char((resultchar%229)-26);
}
}
return decrypted;
}
The syntax to statically initialize an array uses curly braces, like this:静态初始化数组的语法使用大括号,如下所示:
int array[10] = { 0 };
This will zero-initialize the array.这将对数组进行零初始化。
For multi-dimensional arrays, you need nested curly braces, like this:对于多维数组,您需要嵌套的花括号,如下所示:
int cipher[Array_size][Array_size]= { { 0 } };
Note that Array_size
must be a compile-time constant for this to work.请注意, Array_size
必须是编译时常量才能使其工作。 If Array_size
is not known at compile-time, you must use dynamic initialization.如果Array_size
在编译时未知,则必须使用动态初始化。 (Preferably, an std::vector
). (最好是std::vector
)。
You cannot initialize an array to '0' like that您不能像那样将数组初始化为“0”
int cipher[Array_size][Array_size]=0;
You can either initialize all the values in the array as you declare it like this:您可以在声明数组时初始化数组中的所有值,如下所示:
// When using different values
int a[3] = {10,20,30};
// When using the same value for all members
int a[3] = {0};
// When using same value for all members in a 2D array
int a[Array_size][Array_size] = { { 0 } };
Or you need to initialize the values after declaration.或者您需要在声明后初始化值。 If you want to initialize all values to 0 for example, you could do something like:例如,如果要将所有值初始化为 0,则可以执行以下操作:
for (int i = 0; i < Array_size; i++ ) {
a[i] = 0;
}
You can't initialize arrays like this:你不能像这样初始化数组:
int cipher[Array_size][Array_size]=0;
The syntax for 2D arrays is:二维数组的语法是:
int cipher[Array_size][Array_size]={{0}};
Note the curly braces on the right hand side of the initialization statement.请注意初始化语句右侧的花括号。
for 1D arrays:对于一维数组:
int tomultiply[Array_size]={0};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.