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

9
  • You cannot use negative indexes - it is UB. Why are you even trying to do this? Commented Dec 13, 2017 at 6: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++ Commented Dec 13, 2017 at 6:20
  • 2
    Possible duplicate of Array index out of bound in C Commented Dec 13, 2017 at 6: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. Commented Dec 13, 2017 at 6:23
  • 1
    Possible duplicate of Negative array index Commented Dec 13, 2017 at 6:23

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

so [1][-1] is memory address location of [0][4].. okay thanks

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.