简体   繁体   中英

Variadic Adding Function C

I'm writing a simple variadic function that adds together a series of ints and returns the sum. I'm having a bit of trouble understanding how it works and my code doesn't seem to work though I feel I'm in the right direction with my code. (Posted below) The specifications of this function are that it takes at least one param and the last param is always a zero (as seen called in the main). I was also told, based upon my machine, that I wouldn't necessarily get the output I'm looking for which, as you could imagine, further complicates my situation. Some assistance with correcting my Sum() function would be greatly appreciated.

EDIT: This is supposed to be done w/o the use of stdarg.h header and thus no va_arg functions.

int Sum(int a, ... ) {
   int sum = 0, *addy = &a;

   while (*addy) {
      sum += *addy;
      addy += sizeof(a);
   }

   return sum;
}


int main() {
   printf("%d %d %d %d\n", Sum(0), Sum(3, 5, 6, 7, 0),
   Sum(7, 2, 42, 3, 5, -4, 0), Sum(-1, 9, 12, 123, -213, 42, 7, 2, 0));
}
//Expected output: 0 21 55 -19
//My output: 0 32770 32770 32776

When you add a number to an int pointer (as in addy += sizeof(a) ) the number you add is automatically multiplied by the size of whatever type the pointer is declared as (in this case int ). To fix this, just use

addy += 1;

instead. However, I would recommend using variadic macros instead of this method, they are clearer and less error prone.

for variable arguments, you have to use va_start and va_end functions, hope useful..

http://www.gnu.org/software/libc/manual/html_node/Variadic-Example.html#Variadic-Example

Can you please check this

int Sum(int a, ... ) {
 int sum = 0, *addy = &a;

while (*addy) {
  sum += *addy;
  addy ++;
}

return sum;
}


int main() {
   printf("%d %d %d %d\n", Sum(0), Sum(3, 5, 6, 7, 0),
  Sum(7, 2, 42, 3, 5, -4, 0), Sum(-1, 9, 12, 123, -213, 42, 7, 2, 0));
}

Point to remember is for pointer operations: the number you are adding to the pointer will be multiplied by the size of the type that the pointer is pointing to. So incrementing the pointer addy is enough for geting the next element.

 #include <stdarg.h>
 #include <stdio.h>

 int
 add_em_up (int count,...)
 {
   va_list ap;
   int i, sum;

   va_start (ap, count);         /* Initialize the argument list. */

   sum = 0;
   for (i = 0; i < count; i++)
     sum += va_arg (ap, int);    /* Get the next argument value. */

   va_end (ap);                  /* Clean up. */
   return sum;
 }

 int
 main (void)
 {
   /* This call prints 16. */
   printf ("%d\n", add_em_up (3, 5, 5, 6));

   /* This call prints 55. */
   printf ("%d\n", add_em_up (10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10));

   return 0;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM