C varargs across functions: identify the incorrect usage when forwarding varargs and misusing va_start.\n\n#include <stdio.h>\n#include <stdarg.h>\nvoid display(char *s, ...);\nvoid show(char *t, ...);\n\nint main()\n{\n display("Hello", 4, 12, 13, 14, 44);\n return 0;\n}\nvoid display(char s, ...)\n{\n show(s, ...); / attempt to forward ellipsis directly */\n}\nvoid show(char t, ...)\n{\n int a;\n va_list ptr;\n va_start(ptr, s); / wrong anchor, should be 't' */\n a = va_arg(ptr, int);\n printf("%f", a);\n}

Difficulty: Medium

Correct Answer: Error: invalid function show() call

Explanation:


Introduction / Context:
Forwarding variable arguments between functions requires care. You cannot “pass” ... directly; instead you must rebuild the call with explicit arguments or use va_list/va_copy. Moreover, va_start must reference the last named parameter in the definition's parameter list.


Given Data / Assumptions:

  • display attempts show(s, ...), which is not valid C syntax for forwarding varargs.
  • show calls va_start(ptr, s) even though its last named parameter is t, not s.
  • printf("%f", a) prints an int with a %f specifier, which is also mismatched.


Concept / Approach:
The error most centrally tested is in show: va_start must be invoked as va_start(ptr, t), because t is the last named parameter. Additionally, forwarding from display requires building a va_list inside display and then either consuming it there or using va_copy to pass to show. Writing show(s, ...) is invalid.


Step-by-Step Solution:
Fix display to accept va_list forwarding: e.g., have show accept va_list or reconstruct arguments.In show, replace va_start(ptr, s) with va_start(ptr, t).Match printf format with type: use %d for int.


Verification / Alternative check:
Correct patterns include: void vshow(char *t, va_list ap); and calling it from display with va_start/va_copy.


Why Other Options Are Wrong:
Invalid function display() call is also problematic but the more concrete, immediate error flagged is within show (wrong va_start anchor and format mismatch). No error and other distractors ignore these standard violations.


Common Pitfalls:
Trying to forward ... literally, using the wrong identifier in va_start, and mismatching printf formats.


Final Answer:
Error: invalid function show() call

More Questions from Variable Number of Arguments

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion