Can you add an array without square brackets or subscript to an integer? What is the result?

Viewed 975

I was going through an online lecture and I saw this function to sum an array

int arraySum(int array[], const int n)
    {
        int sum = 0, *ptr;
        int *const arrayEnd = array + n;
        ...
    }

I've not seen an array added to an integer before. If n is the size of the array, does array + n mean that arrayEnd is assigned a value of the last element in array[] or does it mean something else like the address of that element?

2 Answers

What you're seeing is pointer arithmetic.

array is a pointer to the start of your array. Assuming the array has n elements, then array + n (or equivalently &array[n]) points to one element past the end of the array.

It is legal to have a pointer to one element past the end of an array, however you can't dereference that pointer.

void f(int array[]) and void f(int* array) are the same thing in C. So you're almost right when you speculate that it's the address of the last element: it's one past that. Meaning it's useful for less than checks, but not to dereference as that might crash or result in a garbage value.

Related