I can not find an error in the code, the function sum , with a variable number of parameters, the first argument takes the number of arguments, then the arguments themselves. In the cycle I refer to the wrong addresses. Help me find a bug.

 #include <stdio.h> void sum(int k, ...) { int *p = &k; int sum = 0; for (int i = 0; i < k; ++i){ ++p; sum += *p; } printf("%d", sum); } int main() { sum(3, 1, 2, 3); return 0; } 
  • 2
    without va_ * macros you cannot make it portable. - Croessmah
  • 3
    @Harry rather, "I want to watch TV. How can I do this? Watch TV not to offer." - Croessmah
  • four
    The above code works under Linux / gcc but only if compiled in 32bit mode. Why? just so the stars were formed - KoVadim
  • 2
    Sorry, not Lviv Polytechnic? There some teacher teaches modern C ++ according to his book, where as a STANDARD of LANGUAGE (!) The implementation of Borland C ++ 3.1 is considered with all its, let's say, features ... - Harry
  • 2
    under 64-bit architecture will not work, because there the parameters are transmitted through the registers (the first 6 pieces), and only then through the stack. Such an agreement. And here is the manipulation of the stack. clang goes further and does it even under a 32bit platform ... - KoVadim

1 answer 1

Something like this:

 #include <stdio.h> #include <stdarg.h> int sum(size_t k, ...) { va_list ap; va_start(ap, k); int sum = 0; while (k--) { int num = va_arg(ap, int); sum += num; } va_end(ap); return sum; } int main() { printf("%i\n", sum(3, 1, 2, 3)); } 

Without stdarg.h will not work everywhere. va_* can read about va_* macros in this question. Your code may or may not work on some platforms. It all depends on how arguments are passed to the function (see calling conventions ).