I have the following code :
#include <cstdarg>
#include <iostream>
using namespace std;
class a {
};
void fun1(a& aa, ...)
{
va_list argp;
va_start(argp, aa);
char *p = 0;
while ((p = va_arg(argp, char *)) != 0) {
cout << p << endl;
}
va_end(argp);
}
void fun2(char *aa, ...)
{
va_list argp;
va_start(argp, aa);
char *p = 0;
while ((p = va_arg(argp, char *)) != 0) {
cout << p << endl;
}
va_end(argp);
}
int main()
{
cout << "fun2" << endl;
fun2("a", "1", "2", (char *)0);
cout << "fun1" << endl;
fun1(a(), "1", "2", (char *)0);
getchar();
}
Everything works fine with fun2. However, fun1 will just crash.
May I know how can I prevent from crashing, at the same time able to use class reference as 1st parameter.
Currently, it prints :
fun2
1
2
fun1
then crash.
I wish
fun2
1
2
fun1
1
2
You can’t use a reference parameter as the last named parameter with va_start. The reason is because va_start takes the address of the named parameter to find the location of the rest of the arguments. However, taking the address of a reference gives the address of the variable pointed at by the reference, not the address of the parameter itself. Your options are:
1) change the variable type from a reference to a pointer (or a non-reference if you are OK with a copy of the passed in variable).
2) Add an additional required parameter so that the reference isn’t the last named parameter. The additional parameter can be a useful parameter, such as one of the char* you are going to pass to your particular function, or it can be a dummy variable you just ignore.
3) Change the definition of va_start. It’s not recommended, but you can do it. See http://support.microsoft.com/kb/119394 for a non-portable redefinition.