0

i have two dimensional array in C++ like this :

int array[2][5] = {
    {1,2,3,4,5},
    {6,7,8,9,10}
};

when i access the index of array[0][4] , of course the result value will be 5. But i still confused when i tried access index of array like this array[1][-1], the result value is 5 too.

Anyone can explain this? thank you

moonPride
  • 141
  • 3
  • 13
  • You cannot use negative indexes - it is UB. Why are you even trying to do this? – Ed Heal Dec 13 '17 at 06:17
  • i just tried for my homework, and it's work i can access negative index with my code, i was compiling the code with dev c++ – moonPride Dec 13 '17 at 06:20
  • Read this. Should answer your question [Negative array index](https://stackoverflow.com/questions/23771001/negative-array-index) – Arun A S Dec 13 '17 at 06:21
  • 2
    Possible duplicate of [Array index out of bound in C](https://stackoverflow.com/questions/671703/array-index-out-of-bound-in-c) –  Dec 13 '17 at 06:22
  • 2
    *i can access negative index with my code* -- And I can drive a car without a driver's license. Doesn't make it legal though. – PaulMcKenzie Dec 13 '17 at 06:23
  • 1
    Possible duplicate of [Negative array index](https://stackoverflow.com/questions/23771001/negative-array-index) – Arun A S Dec 13 '17 at 06:23
  • @PaulMcKenzie i just ask, because i really really dont know why i can access the value with negative index. – moonPride Dec 13 '17 at 07:03
  • @NishikinoMaki -- `array[0][-1]` -- Don't be surprised if this "works". My point is that you can do a lot of things in C++ that are really not legal or what you intended, and things may work, may crash, etc. – PaulMcKenzie Dec 13 '17 at 07:19
  • @PaulMcKenzie ok thanks for advice :) – moonPride Dec 13 '17 at 08:18

2 Answers2

2

It is actually undefined behaviour. The reason why you see 5 is more or less accidental. The reason is that you are creating fixed length two-dimensional array of integers that is created in memory in sequence. Therefore [1][-1] is on some (perhaps most?) implementations equivalent to memory location of [0][4]. In memory it looks like sequence 1,2,3,4,5,6,7,8,9,10 in your case. But it is not guaranteed or defined that multidimentionsonal fixed-length arrays will be always contiguous like what you observes.

Resurrection
  • 3,916
  • 2
  • 34
  • 56
2

It has to do with how index is calculated, The memory itself is an array of words. when you use two-dimension index [i][j] it is mapped to memory as i*size2+j (if array's size was [size1][size2])

so when you calculate this for [0][4] and [1][-1] you get the same value (0*5+4=4,1*5-1=4) two-dimensional array

Gaurav Sehgal
  • 7,422
  • 2
  • 18
  • 34
Raghava Dhanya
  • 959
  • 15
  • 22