我正在尝试使用 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/