char buf[8]; int n = snprintf(buf, sizeof buf, "%s", "abcdefghij"); What are n and the contents of buf?
Correct answer
C. n equals 10, and buf holds the first seven characters plus a terminator
16 views
C. n equals 10, and buf holds the first seven characters plus a terminator
16 views
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.
Asked in: NTS, PPSC IT, Campus Interviews
Not sure why the answer is C? Ask here and get an explanation.