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

Calling sprintf() under a variadic function in C

我想为我正在使用的嵌入式板编写一个快速的 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;
}