I have made a separate function display() for displaying the numbers and wanted to send the initialized argument pointer to this function. I am not getting the expected result. What is going wrong here?
I am using gcc version 10.1.0 (GCC)
/* Expected OUTPUT */
99 + 68 -> Total = 167
11 + 79 + 32 -> Total = 122
23 + 34 + 45 + 56 + 78 -> Total = 236
/* Getting OUTPUT */
99 + 68 -> Total = 224
11 + 79 + 32 -> Total = 1410200528
23 + 34 + 45 + 56 + 78 -> Total = -1056735662
My code is:
/*
* Program in which the variable length
* list is passed to another function
*/
#include <stdio.h>
#include <stdarg.h>
int sum(int, ...);
void display(int, va_list);
int main(void) {
printf("\b\b-> Total = %d\n", sum(2, 99, 68));
printf("\b\b-> Total = %d\n", sum(3, 11, 79, 32));
printf("\b\b-> Total = %d\n", sum(5, 23, 34, 45, 56, 78));
return 0;
}
int sum(int num, ...) {
va_list ap;
int i, arg, total = 0;
va_start(ap, num);
display(num, ap);
for (i = 0; i < num; i++) {
arg = va_arg(ap, int);
total += arg;
}
va_end(ap);
return total;
}
void display(int num, va_list ap) {
int i, argument;
for (i = 0; i < num; i++) {
argument = va_arg(ap, int);
printf("%d + ", argument);
}
}