Are negative array indexes allowed in C?

后端 未结 8 2298
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 13:56

I was just reading some code and found that the person was using arr[-2] to access the 2nd element before the arr, like so:

|a|b|c|         


        
8条回答
  •  旧巷少年郎
    2020-11-22 14:34

    I know the question is answered, but I couldn't resist sharing this explanation.

    I remember Principles of Compiler design: Let's assume a is an int array and size of int is 2, and the base address for a is 1000.

    How will a[5] work ->

    Base Address of your Array a + (index of array *size of(data type for array a))
    Base Address of your Array a + (5*size of(data type for array a))
    i.e. 1000 + (5*2) = 1010
    

    This explanation is also the reason why negative indexes in arrays work in C; i.e., if I access a[-5] it will give me:

    Base Address of your Array a + (index of array *size of(data type for array a))
    Base Address of your Array a + (-5 * size of(data type for array a))
    i.e. 1000 + (-5*2) = 990
    

    It will return the object at location 990. So, by this logic, we can access negative indexes in arrays in C.

提交回复
热议问题