2012-03-22 57 views
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; 
} 

回答

3
char** getCommands(){ 
    char* commands[10]; 
    … 
    return commands; 
} 

聲明return commands不返回數組的,它返回地址數組。從技術上講,commands這個表達式的類型從這個上下文中的array-10-of-pointer-of-char衰減到pointer-to-pointer-to-char;表達式的值是數組的第一個元素的地址。

因此,您返回局部變量的地址,該局部變量在return語句後不再存在。稍後,在loop中,您將此指針取消引用一個銷燬的對象,導致未定義的行爲。

+0

完美,非常感謝!我是一個C++新手,這固定完美! – Chris 2012-03-22 22:02:31