Reputation:
I want to pass variable argument to a function but don't want set the number in argument. so I check the end of argument with 0 as 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 it seems the out put not correct:
str: hello
data: 5.50
data: 4.50
data: 3.50
data: 34498135662005122837381407988349324615424289861359674446209831441373336786008345008385190019649501215393603210517859097842586295826918562939434091794406737728862534747430060032.00
The last data output is random value, it should not there!
Upvotes: 0
Views: 82
Reputation: 229593
When you call the function, you don't provide a 0.0
argument. The function tries to print everything up to a zero argument, but there is not such argument.
The function will go on to look at memory where it would expect a 5th, 6th, ... parameter until one such location randomly contains a zero or the program crashes.
Upvotes: 3
Reputation: 34585
You could solve it by adding a sentinel value to the values passed.
int main()
{
foo("hello", 5.5, 4.5, 3.5, 0.0);
}
This had to be 0.0
in my test, not 0
.
Upvotes: 4