C varargs typing: identify the primary error when the va_list variable is declared with the wrong type and used with va_start.
#include
#include
void varfun(int n, ...);
int main()
{
varfun(3, 7, -11.2, 0.66);
return 0;
}
void varfun(int n, ...)
{
float ptr; / WRONG: should be va_list /
int num;
va_start(ptr, n); / invalid: ptr is not a va_list */
num = va_arg(ptr, int);
printf("%d", num);
}
-
AError: too many parameters
-
BError: invalid access to list member
-
CError: ptr must be type of va_list
-
DNo error
-
ENone of the above
Answer
Correct Answer: Error: ptr must be type of va_list
Explanation
Introduction / Context:Using variable arguments in C requires a dedicated opaque type va_list. You cannot substitute other pointer types for va_list. The macros va_start, va_arg, and va_end are defined to operate only on objects of type va_list.
Given Data / Assumptions:
ptris declared asfloat *.va_start(ptr, n)is invoked withptr.- Subsequent
va_argis called using the wrongptrtype.
Concept / Approach:va_list is an implementation-defined type that stores the state necessary to iterate over unnamed arguments. Treating it as an ordinary pointer (e.g., float *) is invalid and will not compile or will result in undefined behavior. The correct declaration is va_list ptr; followed by va_start(ptr, n);.
Step-by-Step Solution:Replace float *ptr; with va_list ptr;Invoke va_start(ptr, n); to initialize list traversal.Use va_arg(ptr, int) to retrieve the first promoted integer.Finish with va_end(ptr);
Verification / Alternative check:Compiling with a conforming compiler will error on applying va_start to a non-va_list object. Static analyzers flag this immediately.
Why Other Options Are Wrong:Too many parameters is unrelated. Invalid access to list member is vague and not the fundamental issue. No error is incorrect because the type is wrong.
Common Pitfalls:Assuming va_list is just a pointer; it may be a struct or array type internally. Always use the standard macros and types.
Final Answer:Error: ptr must be type of va_list