C Programming - Variable Number of Arguments - Discussion

Discussion Forum : Variable Number of Arguments - Find Output of Program (Q.No. 5)
5.
What will be the output of the program?
#include<stdio.h>
#include<stdarg.h>
void fun1(int num, ...);
void fun2(int num, ...);

int main()
{
    fun1(1, "Apple", "Boys", "Cats", "Dogs");
    fun2(2, 12, 13, 14);
    return 0;
}
void fun1(int num, ...)
{
    char *str;
    va_list ptr;
    va_start(ptr, num);
    str = va_arg(ptr, char *);
    printf("%s ", str);
}
void fun2(int num, ...)
{
    va_list ptr;
    va_start(ptr, num);
    num = va_arg(ptr, int);
    printf("%d", num);
}
Dogs 12
Cats 14
Boys 13
Apple 12
Answer: Option
Explanation:
No answer description is available. Let's discuss.
Discussion:
16 comments Page 2 of 2.

Ram said:   1 decade ago
I didn't understand. Please correct explanation.

Anonymous said:   8 years ago
Here, in void func 1,

va _start( ptr , num ) points to first argument in func 1 ie '1'
str=va_arg (ptr,char*) points to next argument in func 1 ie 'Apple' as there is no loops it directly prints Apple.

In void func2,

va_start( ptr,num) points to first argument in void func2 ie '2'
va_ arg(ptr,int) points to next argument in void func2 ie. '12' as there is no loops it directly prints '12' as output.
So our output is Apple 12.

Ajay said:   8 years ago
According to me,

fun1

num=1
ptr is a va_list variable.
ptr , 1
str copy Apple // ptr=1 so first string copy

Apple //print

fun2

num=2
ptr=2
num= (12+13)/2 // average of first two number
num =12

12 //print

The final answer is;
Apple12.

Saba said:   8 years ago
I didn't understand. Please explain.

Brandon said:   8 years ago
First arg array:

1, "Apple", "Boys", "Cats", "Dogs"

va _start( ptr , 1)

puts the start point at the first element (arg arrays start at 1, not 0), so the start point is the element "1"

va_arg (ptr,char*)

says, return the first element that is a char pointer, which is the second element "Apple*

Second arg array:
2, 12, 13, 14

va _start( ptr , 2)

means the starting point it the second element in the array, "12"

va_ arg(ptr,int)

Means return the first element that is type int from the starting point. Since the element the staring pointer is point to, it returns it which is "12"

The confusion comes from:
1) element 1 is the first element in the array, NOT the element at index 0.
2) the first element is used as both the starting element and counts as an element in the array, it is not "consumed".
3) va_ arg returns the first element which matches the given data type, from the starting point previously set by va_start.

Goroparthi said:   8 years ago
How the answer comes? Please explain.


Post your comments here:

Your comments will be displayed after verification.