0

I'm working with my STM32 but since I'm new to c/c++ (coming from c#) i find string operations a bit difficult.

Until now I'm sending serial like this:

  strcpy((char*)buf, "Unable set read MCP9808\r\n");
  HAL_UART_Transmit(&huart1, buf, strlen((char*)buf), HAL_MAX_DELAY);

But I want to change that to a onliner using Debug function that I made. But im getting error 'strlen' from incompatible pointer type. I want to take inn any string (char array), get its length to set up the buffer and send the data.

    int Debug(char arr[])
    {
        int size = strlen(&arr);
        uint8_t buf[size];
    
        strcpy((char*)buf, arr);

        // the above code is the important part...
        HAL_UART_Transmit(&huart1, buf, strlen((char*)buf), HAL_MAX_DELAY);
    
        return 1;
    }

    Debug("Hello World!\r\n");
Chris
  • 26,361
  • 5
  • 21
  • 42
  • 1
    `strlen(&arr)` is the same as `strlen(char**)` . this is definitely not what you want. Use `strlen(arr)` – fukanchik May 14 '22 at 20:20
  • 2
    Why `uint8_t` if you cast `(char*)buf` all the further code? – 273K May 14 '22 at 20:21
  • 1
    Also read about [why aren't variable-length arrays part of the C++ standard?](https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard) – 273K May 14 '22 at 20:22
  • @273K i dont know, im just smashing together code from the interwebs without really knowing what im doing here... feel free to suggest optimizations :-) –  May 14 '22 at 20:23
  • 3
    You definitely should stop guessing and start from [The Definitive C++ Book Guide and List](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) . – 273K May 14 '22 at 20:24
  • 1
    @fk69 with approach like that chances are you will just fry out your stm32. – fukanchik May 14 '22 at 20:27
  • Or, for C: https://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list – Craig Estey May 14 '22 at 20:29
  • 2
    *"I'm new to c/c++"* -- what is this "c/c++" that you speak of? I am familiar with the C language, and the C++ language, but I am not aware of a "C/C++" language (nor of the "C/C++/C#" language that some others think exists). The distinction between C and C++ is rather important when it comes to string processing. – JaMiT May 14 '22 at 20:54
  • @273K very dangerous advice. A was banned for 6 months (my ban ended today) because I was posting this link and it was considered unfriendly by the mods – 0___________ May 14 '22 at 21:52

1 Answers1

1
  1. You do not need to strcpy at all as the HAL function is blocking.
  2. int size = strlen(&arr); size should be size_t and you need to pass arr not &arr. &arr is giving the address of the local variable arr not the reference stored in this variable.
  3. buff is too short and it has to be one char longer to store terminating null character.
0___________
  • 60,014
  • 4
  • 34
  • 74