C function variable argument length -


i want pass variable argument function don't want set number in argument. check end of argument 0 below:

#include <stdarg.h> #include <stdio.h>  void foo(char* str, ... ) {     printf("str: %s\n",str);     va_list arguments;                          va_start(arguments,str);     while(1) {         double data = va_arg(arguments,double);          if (data == 0) {             break;         }         printf("data: %.2f\n",data);     }     va_end (arguments);     return; }  int main() {     foo("hello", 5.5, 4.5, 3.5); } 

but seems out put not correct:

str: hello data: 5.50 data: 4.50 data: 3.50 data: 34498135662005122837381407988349324615424289861359674446209831441373336786008345008385190019649501215393603210517859097842586295826918562939434091794406737728862534747430060032.00 

the last data output random value, should not there!

you solve adding sentinel value values passed.

int main() {     foo("hello", 5.5, 4.5, 3.5, 0.0); } 

this had 0.0 in test, not 0.


Comments

Popular posts from this blog

c++ - No viable overloaded operator for references a map -

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - Cannot secure connection using TLS -