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?
for addNumber(4, 2) you are using the first parameter as counter which there are 4 parameter to addup but your giving just 1, so the for loop continue reading from the memory expecting more parameter and just pick up ramdom values and add them up.