double equation_count(int count, double number, ...){ double *p_number = &number, result = 0; int i; for(i=1; i <= count; i++){ result+= pow(*p_number,i); p_number++; } return result; } printf("%g",equation_count(2,2.0,3.0)); 

The function must return the sum of real numbers in i degree.

In this case, the result should be 11 , but returns 1 . The problem is somewhere with the data type, because with integers, the function works.

  • one
    To work with a variable number of arguments, always use stdarg - avp
  • one
    That's where, interestingly, legs grow in this manner of trying to access variable arguments as a kind of "array", through double *p_number = &number; . I often see this. Where does this come from? - AnT
  • @AnT By the way, yes. Not met in any literature. So it is also very interesting. - Harry
  • @Harry, well, an example is given in the book "Z. Ya. Shpak - Programming New C", 229 p. This is a book in Ukrainian. The author of the book lectures to us. - Hardc0re
  • one
    @Harry: Well, just the same consideration of memory models could be called useful, if only so that students understand why there are certain concepts and limitations in the language. And then, spoiled by flat memory, the masses do not understand the difference between size_t and unitptr_t . - AnT

1 answer 1

Because it is necessary to do the standard .

 double equation_count(int count, double number, ...) { int i; double result = number; va_list ap; va_start(ap,number); for(i=2; i <= count; i++) { result += pow(va_arg(ap,double),i); } va_end(ap); return result; } int main(int argc, const char * argv[]) { printf("%g",equation_count(3,2.0,3.0,1.0)); } 

I would even do this without dragging the number into the parameter list:

 double equation_count(int count, ...) { int i; double result = 0; va_list ap; va_start(ap,count); for(i = 1; i <= count; i++) { result += pow(va_arg(ap,double),i); } va_end(ap); return result; }