将float转换为sprintf

时间:2016-10-18 14:12:37

标签: c

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

         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 );
}

1 个答案:

答案 0 :(得分:0)

首先使用更安全的替代方案,例如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 *,使用{{ 1}}运算符显然是错误的,而且只能隐藏你犯错的事实。