从字符串转换为无符号字符*会留下垃圾

Casting from string to unsigned char* leaves garbage

本文关键字:字符 字符串 转换 无符号      更新时间:2023-10-16

这是C++新手问题。我有一个Arduino草图,其中包含以下代码来传输蓝牙低功耗UART通知。

command是 5 个字符时,我在蓝牙接收器端得到 5 个字符。但是,当我使用单个字符命令遵循 5 个字符的command时,收到的是单个字符,后跟前一个command的最后 3 个字符。

command -1,0t.我收到的是-1,0t.但接下来command只是r.我收到的是r,0t.

这是怎么回事?我如何只得到"r"?

int BLEsend(String command){
    byte length = sizeof(command);    
    unsigned char* notification = (unsigned char*) command.c_str(); // cast from string to unsigned char*
    Serial.print(length);
    BLE.sendData(UART_SEND, notification, length);
    Serial.print("Notification Sent: "); Serial.println(command);
    delay(100);
    return 1;
}

您还需要将字符串command.c_str()复制到notification

notification = new char[length + 1];
strcpy(notification , command.c_str());

sizeof( ( 不会给你字符串的长度。

您可以改用int length = command.length( );

command.size( );也应该工作。