Are negative array indexes allowed in C?

后端 未结 8 2190
隐瞒了意图╮
隐瞒了意图╮ 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:54

    I'm not sure how reliable this is, but I just read the following caveat about negative array indices on 64-bit systems (LP64 presumably): http://www.devx.com/tips/Tip/41349

    The author seems to be saying that 32 bit int array indices with 64 bit addressing can result in bad address calculations unless the array index is explicitly promoted to 64 bits (e.g. via a ptrdiff_t cast). I have actually seen a bug of his nature with the PowerPC version of gcc 4.1.0, but I don't know if it's a compiler bug (i.e. should work according to C99 standard) or correct behaviour (i.e. index needs a cast to 64 bits for correct behaviour) ?

    0 讨论(0)
  • 2020-11-22 14:57

    This is only valid if arr is a pointer that points to the second element in an array or a later element. Otherwise, it is not valid, because you would be accessing memory outside the bounds of the array. So, for example, this would be wrong:

    int arr[10];
    
    int x = arr[-2]; // invalid; out of range
    

    But this would be okay:

    int arr[10];
    int* p = &arr[2];
    
    int x = p[-2]; // valid:  accesses arr[0]
    

    It is, however, unusual to use a negative subscript.

    0 讨论(0)
提交回复
热议问题