1

what is the meaning of (unsigned char*)&ch in the following function call ?

      HAL_UART_Transmit(&UartHandle, (unsigned char *)&ch, 1, 0xFFFF);

      HAL_StatusTypeDef HAL_UART_Transmit(UART_HandleTypeDef *huart, unsigned char *pData, int Size, long Timeout)
     {
       /*...........Function Body ........*/
     }
user2819759
  • 85
  • 1
  • 9

3 Answers3

3

&ch is an address of some variable, type is unknown given this code. (unsigned int*)&ch is simply casting the result of this expression to a pointer to int.

Michał Szydłowski
  • 3,261
  • 5
  • 33
  • 55
2

It takes the address of the variable ch using the address-of operator &. The resulting address is then converted (cast) to the type unsigned int *, i.e. a pointer to an unsigned int. This only makes sense if

  1. The type of ch was not unsigned int to begin with
  2. The size of ch is at least as large as the size of unsigned int
  3. The called function accepts an unsigned int * argument

Since we can see that the type of the argument is in fact uint8_t *, this is very likely a bug. The cast should either be removed (if ch is of type uint8_t already, which it should be) or changed to uint8_t *. Also, the function's parameter should be const, a transmit function shouln't change its argument.

unwind
  • 391,730
  • 64
  • 469
  • 606
0

Let's say you have a function that takes an argument of type unsigned int *.

You have an object of type int and you want to pass a pointer to this object the function.

int ch = 42;

Then &ch get you an int * to the int object. You cannot pass &ch directly to your function as &ch is of type int * but the function wants a unsigned int *, so you convert it to unsigned int * with a cast:

(unsigned int *) &ch
ouah
  • 142,963
  • 15
  • 272
  • 331