Consecutive arrays

OP: Why the object following the array has to be necessarily another array?

It does not. "... start of a different array ..." is a simplification. The next spec is:

For the purposes of these operators, a pointer to an object that is not an element of an array behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type. C17dr § 6.5.9 7


OP: Couldn't simply be an object which type was the same as the array base type (like an int immediately following an int[])?

Yes.


Firstly, specifying array here does not exclude/forbid a single object. A single object in memory is indistinguishable from an array of size 1.

(Edit: Read this answer for a citation from the standard that explicitly states this when referring to pointers)

Secondly, the standard also tries to clarify the statement you have quoted, with the following footnote indicating scenarios where the rule applies:

Two objects can be adjacent in memory because they are adjacent elements of a larger array or adjacent members of a structure with no padding between them, or because the implementation chose to place them so, even though they are unrelated.

Putting it all together, what the standard tries to say here is that in general, two pointers to dissimilar objects should not compare equal. However, since it is legal to point one beyond an array object in memory, if there happens to be a different (array) object at that location, it is still legal for such a pointer to compare equal to a pointer to the adjacent object. Now, there may or may not be a valid object at this location, because of alignment choices and padding, but if there is one, it is acceptable for these pointers to compare equal.

In your example, if I changed the array to a char, the pointers would probably compare unequal because the compiler would choose to align the int to 4 bytes (on most 32 or 64-bit platforms), thereby introducing padding. This behaviour is still legal according to the standard.

#include <stdio.h>

struct test { char arr[10]; int i; };

int main() {
    struct test t;
    int *p, *q;
    p = (int*)(t.arr + 10);
    q = &t.i;
    if(p == q)
      printf("Equal pointers.");
    else
      printf("Unequal pointers.");
    return 0;
}

Tags:

C

Arrays