0

I'm trying to learn how to handle functions with variable parameters, however I'm having trouble with this code.

The problem is that there must be some error manipulating the positioning of the stack so that it advances to the next parameter.

I think I'm missing something, the code to my understanding should work correctly.

The goal of this code is simply to add the first 2 parameters. You can see it reflected in output expect. How can i do it?

#include <stdio.h>

int add(int num, ...)
{
    int *ptrStack;
    int i;
    int result = 0;

    ptrStack = &num; // I point the stack through the argument
    ptrStack++;      // I move to the first variable parameter

    for (i = 0; i < num; i++)
    {
        result += *ptrStack; // I take the courage, I add it up and I move ...
        ptrStack++;          // ... to the next element on the stack.
    }
    return result;
}

int main()
{
    int s1, s2, s3, s4;

    s1 = add(2, 123, 754, 897);
    s2 = add(2, 45, 72, 23);
    s3 = add(2, 1, 2, 3, 4, 5);
    s4 = add(2, 33, 83);

    printf("Result 1 = %d\n", s1);
    printf("Result 2 = %d\n", s2);
    printf("Result 3 = %d\n", s3);
    printf("Result 4 = %d\n", s4);

    return 0;
}
OUTPUT: 
Result 1 = -272583112
Result 2 = -272583081
Result 3 = -272583040
Result 4 = -494024802

OUTPUT EXPECT:
Result 1 = 877
Result 2 = 117
Result 3 = 3
Result 4 = 116
edw4rd
  • 3
  • 2
  • 1
    You don't use pointers to handle variadic arguments. You use the `va_XXX` macros. – Barmar Jun 18 '22 at 17:39
  • Also don't forget your first argument will be completely different to any others (a "not variable" arg). Might be easier to just use `int add(...) {` so you can treat all arguments the same. – Brendan Jun 19 '22 at 01:03

0 Answers0