C Programming · Interview question

Is it legal to form a pointer to one past the end of an array?

A strong answer

Yes to form and compare it; no to dereference it. The C standard specifically permits computing a pointer to the element one past the last (arr + n) and using it in comparisons, that's the canonical loop sentinel for (p = arr; p < arr + n; p++). But dereferencing that one-past pointer is undefined behavior, and forming any pointer further out, arr + n + 1, or arr - 1 before the start, is itself UB even if you never dereference it. Optimizers rely on these rules, so violating them can produce wrong code at higher optimization levels, not just crashes. The safe pattern is to use one-past only as a non-dereferenced boundary.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

Pointer Arithmetic & Arrays

Why arr[i] is literally *(arr + i), how pointer math scales by type size, and the array-to-pointer decay that loses your size the moment you call a function.

More Pointer Arithmetic & Arrays questions

Browse all 472 interview questions
Is it legal to form a pointer to one past the end of an array? | EmbeddedPrep.io