简体   繁体   中英

Arduino C++, odd array behavior

I have an Arduino that is processing a string by splitting it into an array. For some reason, however, after the processing function returns, the array can only be accessed once before it appears that the values become corrupted. In other words, I can access any element of the array, but when I do, I am unable to access any other elements of the array.

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;
}

The statement return commands doesn't return the value of the array, it returns the address of the array. Technically, the type of the expression commands decays from array-10-of-pointer-to-char to pointer-to-pointer-to-char in this context; the value of the expression is the address of the first element of the array.

As a result, you return the address of a local variable, which local variable ceases to exist after the return statement. Later, in loop , you dereference this pointer to a destroyed object, resulting in undefined behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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