【问题标题】:Casting from string to unsigned char* leaves garbage从字符串转换为 unsigned char* 会留下垃圾
【发布时间】:2014-11-06 13:29:40
【问题描述】:

这是 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;
}

【问题讨论】:

  • 请注意,sizeof(command)不会为您提供字符串的长度。您需要使用length 成员函数。
  • 这就是问题所在!谢谢。你能写一个答案吗,我会接受的。 (我觉得自己像个白痴)。

标签: c++ casting arduino unsigned-char


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 不只是“老”;它包含冗余和缺陷。 (a) 当std::string 已经缓存了长度时,您不需要遍历字符串来查找其长度。所以这种方法是 O(n) 而不是 O(1) - 哎呀! (b) 字符串是二进制安全的,但您的 strlen 长度计数技术不是。 .....总之,有原因我们早就放弃了这些东西;我们不只是因为时间的任意流逝而这样做。此外,strlen(someCString) 是“老”,但 strlen(aCPlusPlusString.c_str())总是很傻。
    • @LightnessRacesinOrbit 你是对的,我把它从我的答案中删除了:) 最好不要再教这个了
    猜你喜欢
    • 2023-03-16
    • 2018-09-18
    • 2018-03-27
    • 1970-01-01
    • 1970-01-01
    • 2016-02-05
    • 1970-01-01
    • 1970-01-01
    • 2012-04-28
    相关资源
    最近更新 更多