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

时间:2018-09-19 11:28:16

标签: c variadic-functions

我想为嵌入式板编写一个快速的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

任何帮助,这是怎么了?

1 个答案:

答案 0 :(得分:6)

如果要转发const id=typeof post ==='number' ? post /* post is number here */: /*post is Post here */post.id; // id is number ,则应使用vsprintf而不是sprintf:

va_list