Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Consecutive arrays

Tags:

arrays

c

I'm curious about a sentence in the C18 standard:

Two pointers compare equal if and only if both are null pointers, both are pointers to the same object (including a pointer to an object and a subobject at its beginning) or function, both are pointers to one past the last element of the same array object, or one is a pointer to one past the end of one array object and the other is a pointer to the start of a different array object that happens to immediately follow the first array object in the address space. § 6.5.9 6

Why does the object following the array have to be necessarily another array? Couldn't simply be an object of the same type as the array base type (like an int immediately following an int[])?

No wonder I've tried this code:

#include <stdio.h>

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

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

And it yields equal pointers. Is this behaviour not guaranteed at all, just an implementation-defined coincidence?

like image 882
Pep Avatar asked Aug 26 '20 09:08

Pep


People also ask

How do you find consecutive arrays?

Method 1 (Use Sorting) 1) Sort all the elements. 2) Do a linear scan of the sorted array. If the difference between the current element and the next element is anything other than 1, then return false. If all differences are 1, then return true.

What is consecutive number in array?

Consecutive numbers are numbers that follow each other in order. They have a difference of 1 between every two numbers. In a set of consecutive numbers, the mean and the median are equal. If n is a number, then the next numbers will be n+1 and n+2.

What is consecutive element?

Here, consecutive elements mean, when we take all the elements in the array they need to form a consecutive sequence.


1 Answers

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.

like image 51
chux - Reinstate Monica Avatar answered Oct 04 '22 05:10

chux - Reinstate Monica