繁体   English   中英

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]='\0';

  if(Serial.available()){
     delay(100);
     while( Serial.available() && i< 99) {
        commandbuffer[i++] = Serial.read();
     }
     commandbuffer[i++]='\0';
  }
  return commandbuffer;
}
char** getCommands(){
  char* commands[10];
  …
  return commands;
}

语句return commands不返回数组的 ,它返回数组的地址 从技术上讲,表达式commands的类型在此上下文中从array-10-of-pointer-to-char衰减到指针指向char。 表达式的值是数组的第一个元素的地址。

因此,您返回局部变量的地址,返回语句后该局部变量不再存在。 稍后,在loop ,您将此指针取消引用到已销毁的对象,从而导致未定义的行为。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM