1. Home
  2. Computer Science MCQs
  3. C Programming
  4. char buf[8]; int n = snprintf(buf, sizeof buf, "%s"…

Added 30 Nov -0001

char buf[8]; int n = snprintf(buf, sizeof buf, "%s", "abcdefghij"); What are n and the contents of buf?

  1. n equals 10, but buf is left holding all ten characters without a terminator
  2. n equals -1, because the output was truncated by the size argument given
  3. n equals 10, and buf holds the first seven characters plus a terminator Correct answer
  4. n equals 7, and buf holds exactly the seven characters that it kept

Correct answer

C. n equals 10, and buf holds the first seven characters plus a terminator

16 views

MCQSEXAM

Explanation

snprintf returns the number of characters that would have been written had the buffer been large enough, excluding the terminating NUL, so the answer is 10 rather than 7. The output is truncated to size minus one characters and always NUL-terminated when the size is non-zero, so buf holds abcdefg. Reading the return value as the stored length is the classic exam error.

Reference

Asked in: NTS, PPSC IT, Campus Interviews

Preparing for an exam?

Doubts & discussion

Not sure why the answer is C? 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