Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are the addresses of array elements guaranteed to increase

Tags:

c

When I define and initialize an Array a:

Is it absolutely absolutely safe, that if (&(a[x]) > &(a[y])) holds, x > y is implied?

I am worried about some weird exceptional memory address stuff I have no idea about.

like image 983
Lavair Avatar asked Dec 18 '22 19:12

Lavair


2 Answers

Yes, this is guaranteed. Section 6.5.8p5 of the C standard regarding Relational Operators states:

When two pointers are compared, the result depends on the relative locations in the address space of the objects pointed to. If two pointers to object types both point to the same object, or both point one past the last element of the same array object, they compare equal. If the objects pointed to are members of the same aggregate object, pointers to structure members declared later compare greater than pointers to members declared earlier in the structure, and pointers to array elements with larger subscript values compare greater than pointers to elements of the same array with lower subscript values.
All pointers to members of the same union object compare equal. If the expression P points to an element of an array object and the expression Q points to the last element of the same array object, the pointer expression Q+1 compares greater than P . In all other cases, the behavior is undefined

So even if you have strange memory layouts, the language guarantees that the address of an array element with a higher subscript will compare greater that the address of an array element with a lower subscript. As long as the array subscripts are valid the comparison will hold.

like image 76
dbush Avatar answered Jan 04 '23 22:01

dbush


Yes. If x>y then &a[x] > &a[y], if both elements of the array exist, or a[x] is one element past the end of the array. Otherwise the behavior is undefined.

Note: I see your question asks the inverse of my above answer. The inverse is also true: if the address is greater, then its index is greater, if the address is a whole number of elements apart. Normally the compiler handles this and &a[x]+1 is &a[x+1]. The compiler translates the +1 in the first expression to adding the number of bytes of the element size.

like image 25
Paul Ogilvie Avatar answered Jan 05 '23 00:01

Paul Ogilvie