Problem with Variable Argument function

Iam getting a runtime error in this , donno whats its cause ... please help me

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

#include <iostream>
#include <cstdarg>

using namespace std;

int main (int argc , char* argv[]) 
{
	int varFunc(float,int, ...);
	varFunc(2.36f, 3, "Jai Shri Ram \n","This is not hello world","\nRather a variable argument's program");
	
	return 0;
}

int varFunc(float iArg ,int roh  , ...)
{
	va_list x;
	va_start(x,roh);
	int i = 0;
	
	while(cout<<i++)   // iam printing  it to count the number of times this loop is executed before the error is caused
	{
		char *rj = va_arg(x,char*);
		if(rj == 0)   	// i think that this statement is never becoming true throughout whole loop
		{
			cout<<"hello";
			break;
		}
		cout<<rj;
		
	}
	
	va_end(x);
	
	return 0;
}



I think there is some problem with that if statement in function varFunc
you took char *rj;

than rj will give you address of *rj it will give you zero only if it fails in va_arg(x,char*).

and please make habit of doing formal declaration of function outside the main() function.
so what should i do to print those argument strings ?
cout << *rj will print your string.
va_arg will not necessary return null if there is no more arguments to read. Isn't roh the number of strings passed in? In that case you can use that to make sure the loop don't run more than roh iterations.

@HiteshVaghani1
cout << *rj; will print the first char in the string.
Last edited on
@Peter87
you are right. thank you for correcting me.
@Peter87 : no , roh is just a normal argument which can be used for any other task , anyways in which case va_arg returns null ?? ... also is there any good article of "variable argument" you know ?

@HiteshVaghani1 : thanks but when i said how can i print them i meant how to rectify that error
Last edited on
va_arg returns null if you give a null pointer as argument.
varFunc(2.36f, 3, NULL);

You have to know, from previous arguments, if there are more arguments to read. You could remember to always pass a null pointer as the last argument, but if you forget to do so things will go wrong. That is one of the problems with va_arg.

If you are using C++11 it could be done much more safely by using variadic templates or std::initializer_list.
@Peter87 : thanks , i'll try to use variadic templates or std::initializer_list
Topic archived. No new replies allowed.