将 float 转换为 sprintf

标签 c

我正在尝试使用 sprintf 将 float 转换为字符字符串,如下所示

         float temperature = getTemperature();

         char array[15];
         sprintf(array, "temperature %f", temperature);

         int length = strlen(array);
         protocol_WriteMessage(length,(unsigned char*)&array);

但是protocol_WriteMessage接受unsigned char *,所以我强制转换它,但是程序崩溃了。

void protocol_WriteMessage( UINT16 wLen, UINT8 *pbData )
{
    UINT16 crc_calc;

    // Calculate transmitt CRC16
    crc_calc = calc_crc16(&pbData[COMM_POS_COMMAND1], wLen-COMM_POS_COMMAND1);

    comm_states.TxActive    = true;          // signal that the Tx_UART is working

    // write data without further checks
    hal_uart_WriteBuffer( wLen, pbData );
}

最佳答案

首先使用更安全的替代方案,例如 snprintf() ,然后从调用中删除运算符的 & 地址。

要使用snprintf(),您需要执行类似的操作

int result;
char array[32]; // This should be big enough

result = snprintf(array, sizeof(array), "temperature %f", temperature);
if ((result == -1) || (result >= sizeof(array))) {
    // It means that array is too small, or some other error
    // occurred such that `snprintf' has returned -1
}

protocol_WriteMessage(length, (unsigned char *) array);

由于数组已经是指向其自身第一个元素的指针,该元素的类型为 char ,因此当像指针一样传递时,它的类型为 char * ,使用& 运算符显然是错误的,并且强制转换只会隐藏您犯了错误的事实。

关于将 float 转换为 sprintf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40110590/

相关文章:

c - 查找迭代器名称的不同方法

c - 如何在 C 中创建派生结构属性

c - 具有特定地址的指针声明

c - 在编译 freeRTOS 期间在函数 vPortStartFirstTask 中收到警告,但程序正在运行

C 函数第二次运行时抛出异常

c - C 中的外部结构

c# - 获取已安装的软件列表

c - 如何在c中输出char数组

c++ - 是否显示Common Item Dialog 或GetOpenFileName? (Win32 API)

java - C 与 Java 中变量的最大值