-4

I have the following array:

int distances[10] = {10, 11, 14, 12, 11, 14, 9, 7, 10, 10};

When I ran this array through this for loop:

for (int j = 0; j <= 20; j++) { std::cout << distances[j] << " "; }

and printed all of the outputs, this was my output:

10, 11, 14, 12, 11, 14, 9, 7, 10, 10, 4196294, 0, -487465136, 30021, 0, 0, 0, 0, -359687355, 26470, 0  

Why are the last 11 elements so varied in size and not in the rest of the array?

gabe rau
  • 3
  • 2
  • 3
    Hello. Can we see the loop please? – Chelmy88 Aug 21 '19 at 10:07
  • 2
    Looks like you looped 11 times, not 10! – 42LeapsOfFaith Aug 21 '19 at 10:09
  • 2
    `7` is missing from the output. – KamilCuk Aug 21 '19 at 10:09
  • 1
    Hello and welcome to StackOverflow. Please take some time to read the [help page](https://stackoverflow.com/help), especially the sections named [How to Ask](https://stackoverflow.com/help/how-to-ask). You might also want to learn about [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). You didn't include the loop you are actually using and that is probably the problem in your code. – Tarick Welling Aug 21 '19 at 10:11
  • Your array only contains 10 elements (indexed 0 to 9) but your loop iterates 20 times (0 to 19). Iterating past the end of an array means you are reading undefined memory locations, that's why you get the random numbers. – Tony Aug 21 '19 at 10:57
  • Read this: https://stackoverflow.com/questions/1239938/accessing-an-array-out-of-bounds-gives-no-error-why – chtz Aug 21 '19 at 10:57

1 Answers1

0

Your array contains 10 elements (indexed 0 to 9)

int distances[10] = {10, 11, 14, 12, 11, 14, 9, 7, 10, 10};
                     ^   ^   ^   ^   ^   ^   ^  ^  ^   ^
                     0   1   2   3   4   5   6  7  8   9

but your loop iterates 20 times (0 to 19)

int distances[10] = {10, 11, 14, 12, 11, 14, 9, 7, 10, 10}; ?      ?
                     ^   ^   ^   ^   ^   ^   ^  ^  ^   ^    ^      ^
                     0   1   2   3   4   5   6  7  8   9    10 ... 19

Iterating past the end of an array means you are reading undefined memory locations, which is why you get the random numbers - it's data being interpreted as integers.

You can calculate the number elements in the array using

sizeof(distances)/sizeof(distances[0])

but if you are using C++11 you should be able to use

for(int distance : distances)

Search for related questions here on stackoverflow, such as the Correct way of loop through the C++ arrays and Accessing an array out of bounds gives no error, why?

Tony
  • 9,672
  • 3
  • 47
  • 75