1
我有一個Arduino正在處理一個字符串,將它分解成一個數組。但是,出於某種原因,處理函數返回後,只能在數組出現損壞之前訪問數組。換句話說,我可以訪問數組的任何元素,但是當我這樣做時,我無法訪問數組中的任何其他元素。Arduino C++,奇數行爲
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;
}
完美,非常感謝!我是一個C++新手,這固定完美! – Chris 2012-03-22 22:02:31