-1

Given this code:

#include <iostream>
using namespace std;
int main() {
    int examplearray[] = {1,2,3};
    for (int i = 0; i < 6; i++) {
        cout << examplearray[i] << "\t";
    }

    return 0;
}

I have the following output: 1 2 3 3 4200928 6422336

I am pretty sure this is answered somewhere, but I have been browsing Google for a while and I can't find an explanation for this. I haven't defined a value for the 4th and 5th positions of the array, and I assumed it's value would be 0 or NULL . Why do they have random values?

I noticed this when I was trying to make a code like this:

for(int i = 0; examplearray[i] != 0; /* while it's not empty */i++){
    /* do something */
}

How can I do something like I wanted to do on this code?

xacobe97
  • 51
  • 1
  • 5
  • 2
    You're reading off the end of the array which yields undefined behaviour, you're just reading out garbage values that happen to be there in memory – EdChum May 18 '17 at 08:52
  • _and I assumed it's value would be 0 or NULL_: your assumption is wrong. The array has a length of 3 and you are reading beyond the en of the array. – Jabberwocky May 18 '17 at 08:54

2 Answers2

1

If you trying to access array index out of bound, It's undefined behaviors in C and C++. It means there's no guarantee as to what will happen.

msc
  • 33,420
  • 29
  • 119
  • 214
1

For int examplearray[] = {1,2,3};, the length of the array is not specified explicitly, then will be determined according to the intializer list; the result is 3. So trying to access the 4-6th elements (which don't exist at all) is undefined behavior.

If you suppose the length of array is 6 you should write int examplearray[6] = {1,2,3};. For this case the remaining elements would be initialized as 0.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • Okay so now when I define a bigger size for the array i get 0 from the undefined elements of the array. This was what I was looking for. Thank you! – xacobe97 May 18 '17 at 08:57