It's because arrays start at index 0 instead of index 1.
When you declare your
int index[];
on line 13, your array becomes:
1 2
|
Element: [Junk][Junk][Junk][Junk][Junk]...[Junk][Junk][Junk]
Index: 0 1 2 3 4 ... 17 18 19
|
Your array hold 20 slots, BUT since the first slot is 0 instead of 1, that means that the last slot is 19 instead of 20. Also, the uninitialized slots still contain junk data in them.
Now your program runs and you fill in some values, and it updates the length variable:
1 2
|
Element: [ 11 ][ 23 ][ 54 ][Junk][Junk]...[Junk][Junk][Junk]
Index: 0 1 2 3 4 ... 17 18 19
|
and length becomes = 3.
When you try to access
list[length] now, you are trying to access list[3].
list[3] means the
4th element of the list, which still contains junk (in your case, the junk happened to be -85693460)*. Hope that sheds some light.
*This is called undefined behavior, and could actually cause your program to become invalid or do weird stuff (but most likely either segfault/crash or give junk values).