+ 1

Array initialization question

I have a quick question about a code here. In the following code, the array "field" is initialized to equal {0}: "#include <iostream> using namespace std; const int M = 20; const int N = 10; int field[M][N]={0}; int main(){ field[10][5]=1; for(int i = 0; i<M; i++){ for(int j = 0; j<N; j++){ cout<<field[i][j]<<endl; } }; return 0; }" The output was a bunch of 0s until field[10][5], as expected. Then I changed the code slightly here: "#include <iostream> using namespace std; const int M = 20; const int N = 10; int field[M][N]={1}; int main(){ field[10][5]=0; for(int i = 0; i<M; i++){ for(int j = 0; j<N; j++){ cout<<field[i][j]<<endl; } }; return 0; }" This output a single "1" followed by many "0"s. Does this mean uninitialized elements of an array are automatically 0?

1st Oct 2017, 8:09 PM
21kHzBANK21kHZ
21kHzBANK21kHZ - avatar
4 Réponses
+ 3
When you init an array with {x}, the compiler is going to set the first element in the array to x, and everything else to 0 by default. I disassembled it, the compiler produced this code: mov rdi, rsi mov esi, eax mov dword ptr [rbp - 68], eax call memset mov dword ptr [rbp - 64], 1 So effectively, the compiler is calling memset on the array past the first 4 bytes to fill it with zeros (eax was set to 0), and then setting the first 4 bytes of the array to 1.
1st Oct 2017, 8:57 PM
aklex
aklex - avatar
- 1
Thanks for the reply. Does this mean that a declared array with no definition like "field[M][N]" will also be given a bunch of 0s , or does it need a definition like "={0}"?
1st Oct 2017, 9:15 PM
21kHzBANK21kHZ
21kHzBANK21kHZ - avatar
- 1
Without an definition up front when declared, the whole array will remain uninitialized, and so the values of all the elements will be whatever the stack currently contains at those memory locations. Some compilers do set the whole stack to a certain value, typically to the value of a breakpoint so that any rogue code cannot be executed or for debugging purposes. This also applies after the array has been declared. If you have the example: int field[M][N]; field[0][0] = 1; The rest of the array will not be initialized, while [0][0] will be initialized.
1st Oct 2017, 9:29 PM
aklex
aklex - avatar
- 1
Ok, thanks that's good to know. To be sure, I'll get into the habit of initializing arrays to "={0}".
1st Oct 2017, 11:12 PM
21kHzBANK21kHZ
21kHzBANK21kHZ - avatar