Why doesn't the following code work?
#include <stdarg.h>
#include <stdio.h>
// People are missing this in their reponses.... 'fmt' here is passed by
// reference, not by value. So &fmt in _myprintf is the same as &fmt in
// myprintf2. So va_start should use the address of the fmt char * on the
// stack passed to the original call of myprintf2.
void _myprintf(const char *&fmt, ...)
{
char buf[2000];
//---
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
//---
printf("_myprintf:%sn", buf);
}
void myprintf2(const char *fmt, ...)
{
_myprintf(fmt);
}
void myprintf(const char *fmt, ...)
{
char buf[2000];
//---
va_list ap;
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
//---
printf(" myprintf:%sn", buf);
}
int main()
{
const char *s = "string";
unsigned u = 11;
char c = 'c';
float f = 2.22;
myprintf("s='%s' u=%u c='%c' f=%fn", s, u, c, f);
myprintf2("s='%s' u=%u c='%c' f=%fn", s, u, c, f);
}
I expected both lines of output to be the same, but they differ:
myprintf:s='string' u=11 c='c' f=2.220000
_myprintf:s='string' u=2020488703 c='c' f=0.000000
I thought va_start()
used the address of the fmt
variable, which should be the address of the string pointer on the stack.