1. Home
  2. Computer Science MCQs
  3. C Programming
  4. int a[5]; int *p = a + 5; is this pointer valid?

Added 30 Nov -0001

int a[5]; int *p = a + 5; is this pointer valid?

  1. No; any pointer beyond the last element is undefined behaviour even if not dereferenced
  2. Yes, and *p reads the value immediately after the array
  3. No; p must be assigned a[4] because arrays are zero-based
  4. Yes; forming a pointer one past the last element is allowed, but dereferencing it is not Correct answer

Correct answer

D. Yes; forming a pointer one past the last element is allowed, but dereferencing it is not

13 views

MCQSEXAM

Explanation

One-past-the-end pointers are expressly permitted so that half-open ranges from a to a + 5 work, but the location holds no object, so dereferencing or stepping further is undefined. Comparing against a + 5 is well defined, which is exactly what for (p = a; p != a + 5; ++p) relies on. The element a[5] itself is out of bounds and must never be accessed.

Reference

Asked in: NTS, PPSC IT, Campus Interviews

Preparing for an exam?

Doubts & discussion

Not sure why the answer is D? Ask here and get an explanation.

Ask a doubt about this MCQ

Shown after review. No links please.

More C Programming MCQs

Practise all C Programming MCQs

Similar MCQs