0

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?

12
  • Why is this tagged with c++? Commented Aug 27, 2020 at 20:41
  • 3
    1) "When I call the function addNumbers(4, 2, 4, 7, 10), it outputs 23, which is also incorrect because it should be 27" What? 2 + 4 + 7 + 10 = 23. Why should the answer be 27? 2) "This issue is that when I get the output of addNumbers(4, 2), the output is 14823901." Undefined behavior is undefined. Commented Aug 27, 2020 at 20:43
  • 1
    You are using the first parameter as the count of numbers to add, but that's not the result you seem to be expecting. Commented Aug 27, 2020 at 20:43
  • 2
    addNumbers(4, 2) since you use the first number as argument to va_start you 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 behavior Commented Aug 27, 2020 at 20:44
  • 1
    Did you create this addNumbers function, or did you get it from somewhere? Commented Aug 27, 2020 at 21:02

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.