C++ error: “Array must be initialized with a brace enclosed initializer”

匿名 (未验证) 提交于 2019-12-03 02:20:02

问题:

I am getting the following C++ error:

array must be initialized with a brace enclosed initializer  

From this line of C++

int cipher[Array_size][Array_size]; 

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; } 

回答1:

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. If Array_size is not known at compile-time, you must use dynamic initialization. (Preferably, an std::vector).



回答2:

You cannot initialize an array to '0' like that

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:

for (int i = 0; i < Array_size; i++ ) {     a[i] = 0; } 


回答3:

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}; 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!