为什么下面的代码不工作?我可以通过引用来传递va_start()吗?
#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);
}
我期望输出的两行是相同的,但它们的区别:
myprintf:s='string' u=11 c='c' f=2.220000
_myprintf:s='string' u=2020488703 c='c' f=0.000000
我想va_start()
使用的fmt
变量的地址,这应该是字符串的地址指针上堆栈。
偏题:请谨慎使用前面的下划线。它们通常意味着图书馆实施层面的一些东西。在这种情况下,我认为您已经违反了在全局名称空间中保留前面的下划线以供实现使用的规则。更多这里:http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-ac-identifier/228797#228797 – user4581301
不是一个无效C代码的C问题' _myprintf(const char *&fmt,...)'建议选择一种语言。如果C使用'void _myprintf(const char * fmt,...)' – chux
以下划线开头的名字在文件级保留。不要使用它们。 – Olaf