LearnFrenzy
Sign in Take a free test

Variable Number of Arguments · Predict the Output · Question 6

Return value of a vsnprintf-based wrapper Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

What is the output of the following C program?

main.c
#include <stdarg.h>
#include <stdio.h>

int fit(char *buf, size_t size, const char *fmt, ...) {
    va_list ap;
    va_start(ap, fmt);
    int n = vsnprintf(buf, size, fmt, ap);
    va_end(ap);
    return n;
}

int main(void) {
    char b[8];
    int n = fit(b, sizeof b, "%s-%04d", "INV", 42);
    printf("%d [%s]\n", n, b);
    return 0;
}
  • A 8 [INV-004] Correct
  • B 7 [INV-004]
  • C 8 [INV-0042]
  • D 3 [INV]
Correct Answer: Option A

The full text "INV-0042" has 8 characters; the buffer keeps 7 plus '\0'. vsnprintf, like snprintf, returns the length it needed.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links