0

If i create an array as:

int number[10];
for(i=0;i<7,i+=1)
{
    cin>>number[i];
}

Then what will be the values stored in number[j], where j=8,9. And if some value is stored why and how are such values stored??

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335

4 Answers4

2

The answer depends on what storage duration the array has.

If it has the static storage duration when all its elements are zero initialized when the array is declared.

int number[10];

If the array has the automatic storage duration that is declared in a function without having the specifier static or extern when all its elements have indeterminate values.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

They are uninitialized, meaning there could be any number stored in it, and you shouldn't rely on their value for anything.

Some compilers/systems might write zeros or certain patterns into it when running in debug mode, but you should never rely on that.

Demosthenes
  • 1,515
  • 10
  • 22
  • "there could be any number stored in it" is far too generous. It's undefined. – Deduplicator Feb 27 '18 at 13:11
  • I disagree. It is undefined which number is stored means precisely that any number could be stored in it. The behaviour of the program is, of course, undefined as soon as uninitialized data is accessed... – Demosthenes Feb 27 '18 at 13:16
0

The values for number[8] and number[9] will be so called "garbage" value, which means it can be any number that is currently present in that location.

However if you initialize the array with partial initialization:

int number[10] = {1, 2, 3, 4, 5, 6, 7, 8};

Then the last 2 elements will be 0.

user3437460
  • 17,253
  • 15
  • 58
  • 106
0

Modern software loaders clear the bits of a process' memory before turning it over to them. In that case, the values would be zero.

However, if you are cross-compiling, you cannot assume that the foreign loader will zero the bits. Always assign a value to a variable before using it (even if you're not cross-compiling).

shawnhcorey
  • 3,545
  • 1
  • 15
  • 17