Arduino C++,奇怪的数组行为

Arduino C++, odd array behavior

本文关键字:数组 C++ Arduino      更新时间:2023-10-16

我有一个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中,将此指针取消引用到已销毁的对象,从而导致未定义的行为。