爲什麼下面的代碼不工作?我可以通過引用來傳遞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