1
#include <iostream>
using namespace std;
int main()
{
  int a[6];
  for(int i=0;i<6;i++)
  {
    cout <<a[i]<<" ";
  }
  cout << endl;
  return 0;
}

I have a simple piece of c++ code as above. The array is created on the stack and not initialized.

I got the following output: 0 0 0 0 1569540800 32767.

I don't really understand where the last two numbers come from. More specifically,I don't know what are the values in a[4] and a[5]. And I tried to run the program multiple times. a[4] is changing every time while a[5] is always 32767.

I also tried to create an uninitialized array with length of 4 and 8. In these cases, the output is all zeros.

I understand that an array must be initialized. I ran into this situation when I played around with c++ array. I just want to have a deeper understanding of what's going on in memory.

My environment is clang++ on a Mac.

Ziyou WU
  • 13
  • 5

3 Answers3

1

The array a[6] has to be initialized. By default this will be uninitialized. Therefore none of its elements are set to any particular value,their contents are undetermined at the point the array is declared.

To get rid of the redundant data just initialize your array.

Pabdev
  • 406
  • 3
  • 14
0

Uninitialized means that it contains whatever was at that memory location. That is, it can contain anything.

That's why you should always initialize variables.

drRobertz
  • 3,490
  • 1
  • 12
  • 23
0

I believe if an array element is not explicitly initialized it can be anything, typically what was already in that memory address.

In other words, If you don't initialize them, they equal whatever is stored in that memory location. in other other words, garbage.

msc
  • 33,420
  • 29
  • 119
  • 214
  • 2
    They don't equal anything. The contents of the array could appear to change , `a[1] == a[1]` could yield `false`, or any other behaviour at all – M.M Sep 12 '16 at 05:48