在 C 中的可变参数函数下调用 sprintf()



我想为我正在研究的嵌入式电路板编写一个快速printf()函数,其中输出终端是串行端口。我尝试了这样的事情:

int32_t printfDebugSerial(const char *format, ...)
{
char tempBuff[256];
memset(tempBuff, 0, sizeof tempBuff);
va_list arg;
int32_t done;
va_start (arg, format);
done = (int32_t)sprintf(tempBuff,format, arg);
va_end (arg);
HAL_sendToSerial((uint8_t*)tempBuff, strlen(tempBuff)); // writes bytes to serial port
return done;
}

但是当我调用它时,我得到的输出如下:

printfDebugSerial("Hello = %u", 1234);

输出:

Hello = 536929228

然后称为:

printfDebugSerial("Hello = %f", 934.3245);

输出:

Hello = 0.000000

任何帮助,这里有什么问题?

如果要转发va_list,则应使用 vsprintf 而不是 sprintf:

int32_t printfDebugSerial(const char *format, ...)
{
char tempBuff[256];
memset(tempBuff, 0, sizeof tempBuff);
va_list arg;
int32_t done;
va_start (arg, format);
done = (int32_t)vsprintf(tempBuff,format, arg);
va_end (arg);
HAL_sendToSerial((uint8_t*)tempBuff, strlen(tempBuff)); // writes bytes to serial port
return done;
}

最新更新