0

If not declare value in an array, then what value hold on the memory address.

Where did these outputs come from?

int main()  
{
int a[10];
cout<<a[2]<<endl;
cout<<a[2]<<endl;
cout<<a[3]<<endl;
cout<<a[3]<<endl;
return 0; 
}
//Given Output
//1978190368
//1978190368
//1129149863
//1129149863
nafischonchol
  • 104
  • 1
  • 9
  • It's undefined, anyvalue. – Tony Tannous Aug 29 '19 at 07:37
  • Then, Where did these outputs come from? – nafischonchol Aug 29 '19 at 07:40
  • Most probably garbage left from other program runs. – Tony Tannous Aug 29 '19 at 07:42
  • But it gives me same output for same key. Then, how it is garbage? – nafischonchol Aug 29 '19 at 07:44
  • Physical memory always contains *something*, and it always contains the last thing that was written there. – molbdnilo Aug 29 '19 at 07:45
  • In C++ arrays are indexed from ***zero*** to `n - 1`. So for `int a[10];` the valid indexes are `{0, 1, 2, 3, ..... 9}` Where do you assign any value to any element of the array? You didn't initialize the array as all zeros, e.g. `int a[10] = {0};`. At least then your would avoid Undefined Behavior, but all elements would be zero (not very exciting). Why not `for (int i = 0; i < 10; i++) a[i] = i * 2;` Now the array is initialized to all even-numbers less than `20`. Until a variable is initialized, they just contain garbage-values. `1978190368` looks like a good garbage value to me. – David C. Rankin Aug 29 '19 at 07:48
  • 1
    I give you a box that you can store things in, but I also left something in it that I don't care about any more. I don't tell you what it is, and you don't replace the contents. Do you expect the box to contain different things every time you look inside it, or will it just be whatever I put there? – molbdnilo Aug 29 '19 at 07:55
  • What you did there was declaring a local array on the stack frame of the current function (main). The content of the array members is whatever was written to the addresses at the stack frame before the declaration of the array. – Trickzter Aug 29 '19 at 13:32

0 Answers0