Arduino:字符串连接困难
Arduino: Difficulty with String concatenation
我(错)使用Arduino字符串类。我的整个程序:
void setup() {
Serial.begin(9600);
}
void loop() {
const String args[3] = {
"foo", "bar", "baz" };
String result = "";
Serial.println(result);
result += args[0];
Serial.println(result);
result += args[1];
Serial.println(result);
result += args[2];
Serial.println(result);
Serial.println();
}
这个打印:
foo
foobar
foobarbaz
foo
foobar
foobarbaz
foo
foobar
foobarüÿ
foo
foobar
foobarüÿ
foo
foobar
foobar
foo
foobar
foobarüÿ
foo
foobar
foobarüÿ
foo
foobar
foobarüÿ
我不知道为什么它不总是打印:
foo
foobar
foobarbaz
我做错了什么?
Update:我尝试添加第四个字符串到数组。现在程序在通过loop()
大约15次后停止运行。
更新2:以下是String
附加操作符的代码:
const String & String::operator+=( const String &other )
{
_length += other._length;
if ( _length > _capacity )
{
char *temp = (char *)realloc(_buffer, _length + 1);
if ( temp != NULL ) {
_buffer = temp;
_capacity = _length;
} else {
_length -= other._length;
return *this;
}
}
strcat( _buffer, other._buffer );
return *this;
}
更新3:如果我替换:
String result = "";
:
String result = args[0];
问题消失了。有趣。
奇数字符是堆内存损坏的结果。
你的代码没有问题。这是当前Arduino软件使用的内存分配例程版本存在缺陷的表现。它目前与AVR Libc 1.6.4一起发布,其中包含许多在最新的1.7.1版本中修复的内存分配问题。
我使用对Arduino软件的teensyduino增强在teensyduino 2.0板上成功运行了此代码(即没有显示奇数字符)。这包含了对这些内存问题的修复,但不幸的是,这些修复不适用于编程Arduinos。
有计划在2011年8月将官方Arduino软件升级到最新的AVR Libc。
这看起来像是内存被覆盖的典型症状。您必须查看程序的其他部分才能找到罪魁祸首,因为您在这里显示的任何内容都不会导致此问题。
除此之外,您发布的手册页不建议String支持+=操作符。
相关文章:
- 在 c++ 中连接字符串和整数,以便在 C++ 11 不支持计算机的情况下读取多个文件
- 这两个C++语句连接字符串有什么区别?
- 连接字符串族
- 如何使用 + 运算符连接字符串
- 如何按照 Google C++风格指南连接字符串文字?
- 我的字符串类的 += 运算符有问题,它没有正确连接字符串
- 如何编写模板函数来添加整数但连接字符串和字符类型?
- 无法创建栅格堆栈,因为我无法连接字符串(dir_name + 文件名)
- 如何在不使用对象的情况下连接字符串、整数和浮点数
- 在std :: string中连接字符串的选项
- 连接字符串的最佳方法是什么?
- 在实体框架C /CLI上配置连接字符串
- 在 c++ 中连接字符串和 int
- 如何连接字符串并传递给 system() 调用
- 有没有办法方便地为 Winsock send() 生成 HTTP 标头,而不是手动连接字符串
- 在可变参数模板函数中连接字符串(和数字)
- 连接字符串时出现意外问题
- 如何在 c++ 中连接字符串
- 自动连接字符串和 int C++
- 我的c++程序在我不告诉他的地方连接字符串