I'm learning C, and I created a simple addNumbers(int num, ...) function, that takes any number of int arguments, and returns the sum of them.
This issue is that when I get the output of addNumbers(4, 2), the output is 14823901. Which is obviously incorrect.
When I call the function addNumbers(4, 2, 4, 7, 10), it outputs 23, which is also incorrect because it should be 27, but at least it's closer.
Here's my code:
#include<stdio.h>
#include<stdarg.h>
// Functions with variable number of arguments
int addNumbers(int num, ...)
{
int i;
int sum = 0;
// List to hold variable amount of parameters
va_list parameters;
// Initialize "parameters" list with arguments
va_start(parameters, num);
for(i = 0; i < num; i++)
{
// Adds each "int" argument from "parameters" to sum
sum += va_arg(parameters, int);
}
// Cleans memory
va_end(parameters);
return sum;
}
int main()
{
printf("%i", addNumbers(4, 2, 4, 7, 10));
return 0;
}
Should I not be using va_list, va_arg, etc...?
What's the best way to be able to take in a variable number of arguments?
addNumbers(4, 2, 4, 7, 10), it outputs23, which is also incorrect because it should be27" What?2 + 4 + 7 + 10 = 23. Why should the answer be27? 2) "This issue is that when I get the output ofaddNumbers(4, 2), the output is14823901." Undefined behavior is undefined.addNumbers(4, 2)since you use the first number as argument tova_startyou end up "lying" to the function about how many arguments you passed in. So then your loop tries to access values that don't exist, which is undefined behavioraddNumbersfunction, or did you get it from somewhere?