从字符串转换为无符号字符*会留下垃圾
Casting from string to unsigned char* leaves garbage
这是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( );
也应该工作。
相关文章:
- 从 argv[1] 转换为字符 * 字符串后有什么问题?
- 将 NULL 与 C 的字符* 字符串一起使用
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- 无法将常量字符字符串传递给模板类
- 如何组合一个宽字符字符串,中间插入一些空字符
- 如何将二维数组类型字符(字符串)作为函数参数传递?
- 从给定索引返回子字符字符串的函数
- 字符 [](c 字符串)的初始化标准
- 如何将字符字符串用作数学运算符
- 将 Unicode 字符/字符串写入文件
- C++,字符* 字符串修改
- 如何有效地用不同的整数元素替换字符字符串的元素
- C++:如果我们在字符串中添加一些整数,为什么它会从开头删除该数量的字符?(字符串 + 整数)
- strcpy正在复制sth字符i字符串.如何解决此错误
- 在C++中将双精度转换为字符*/字符串
- C 中的宽字符字符串
- 如何提取C 中的字符/字符串之间的字符串
- 无法将字符/字符串转换为int
- 带有指针的反转字符字符串
- 反转字符串中的 n 个字符(字符串中没有空格),而不使用 c++ 中的内置函数