Are a variable and an array with 1 element equal with pointer arithmetic?

Viewed 18

Consider following small function:

int sum_array(const int *data, size_t len) {
    int sum = 0;
    for (const int *end = data+len; data != end; ++data) {
        sum += *data;
    }
    return sum;
}

If we call it like this:

int data1[] = { 1 };
int result1 = sum_array(data1, 1);

This is fine, data + 1 in the function is fine, because it is legal to have a pointer to 1 step beyond the end of an array.


However, if we call it like this:

int data2 = 1;
int result2 = sum_array(&data2, 1);

Is this still fine, data + 1 still ok? That is, is it legal to have a pointer pointing to an address beyond a non-array variable?

0 Answers
Related