Arduino C++,奇怪的数组行为
Arduino C++, odd array behavior
我有一个Arduino,它通过将字符串拆分为数组来处理字符串。然而,由于某种原因,在处理函数返回后,在值出现损坏之前,只能访问一次数组。换句话说,我可以访问数组的任何元素,但当我访问时,我无法访问数组的其他任何元素。
void loop(){
int pin;
Serial.print("Enter command: ");
while(Serial.available()<=0)
delay(100);
///Input to the serial terminal was: "This;is;a;command". Notice how inside the getCommands() function, it will output all elements ok
char** commands = getCommands();
Serial.println(commands[1]); ///prints "is"
Serial.println(commands[0]); ///**** prints nothing, or sometimes infinite spaces****
delay(1000);
}
char** getCommands(){
char* commandIn = getSerialString();
char* commands[10];
char *str;
int i=0;
while ((str = strtok_r(commandIn, ";", &commandIn)) != NULL){
commands[i]=str;
i++;
}
Serial.println(commands[0]); ///prints "This"
Serial.println(commands[1]); ///prints "is"
Serial.println(commands[2]); ///prints "a"
return commands;
}
char* getSerialString(){
while(Serial.available()<=0)
delay(100);
int i=0;
char commandbuffer[100];
for(int a=0; a<100; a++)
commandbuffer[a]=' ';
if(Serial.available()){
delay(100);
while( Serial.available() && i< 99) {
commandbuffer[i++] = Serial.read();
}
commandbuffer[i++]=' ';
}
return commandbuffer;
}
char** getCommands(){
char* commands[10];
…
return commands;
}
语句return commands
不返回数组的值,而是返回数组的地址。从技术上讲,在这种上下文中,表达式commands
的类型从指针到字符的数组-10衰减为指针到指针到字符;表达式的值是数组的第一个元素的地址。
因此,您返回一个局部变量的地址,该局部变量在return语句之后就不存在了。稍后,在loop
中,将此指针取消引用到已销毁的对象,从而导致未定义的行为。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '