anni11's blog

By anni11, history, 7 years ago, In English

Hello friends, although this is a silly doubt but i have faced some problems because of this.

I have seen that many coders when they code their solutions ,they use the arrays they have declared without initializing it with zero i.e. they write code as if the array already contains zero at all indices while i initialize it with zero, so my doubt is that when we declare a 1-D array or 2-D array or any N-D array then is it automatically initialized with zero at all locations or some random values. And is it always true in all the online judges or do we need to initialize it with zero to eliminate the random values ? For eg when i write the following :

int a[10];

for(int i = 0; i < 10; ++i) cout << a[i] << endl;

I get random values and sometimes zero. Could anyone tell me what is exactly happening. Thanks.

  • Vote: I like it
  • +11
  • Vote: I do not like it

»
7 years ago, # |
Rev. 2   Vote: I like it +4 Vote: I do not like it

If you put your array inside a function, you can get random values, because this array is created on the stack, which is not cleaned:

Code

But if your array will be declared at global scope (or it will be static), it will be initialized with zeros (though it's not guaranteed). Thus, the following two codes will output 10 zeros:

Code1
Code2

But I recommend you ALWAYS to initialize arrays with zeros. Like this:

Code

This code will output 10 zeros.

Or use vectors, they are automatically cleaned.