Andre Andre - 1 month ago 7
C Question

converting float to sprintf

I'm trying to convert a float to char string I used sprintf, as the following

float temperature = getTemperature();

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

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


but protocol_WriteMessage accepts unsigned char *, so I casted it, but the program crashes.

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

Answer

First of all use a safer alternative like snprintf(), and then remove the & address of operator from the call.

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

since array is already a pointer to the first element of itself, which is of type char then it's type is char * when passed like that as a pointer, using the & operator is clearly wrong and casting only hides the fact that you made a mistake.

Comments