Hi there,
The following code is using strtok and strtok_r to split a string containing pairs of keys and values and store the result in a predefined multidimensional char global array.
All looks good when I examine the array from within the split function, correct values are in place, but when I check the array right after that in loop(), the values are not there, instead I get junk.
This symptom do no occur when I replace strtok_r with any char value so I can only assume I am doing something wrong with the call to strtok_r, but obviously it could be something else.
Thanks in advance for helping!
char * ca[5][2];
String myString = "a=red;b=green;c=blue";
void setup() {
Serial.begin(115200);
while (!Serial);
// reseting array
int i;
for (i = 0; i < 5; i++) {
ca[i][0] = "x";
ca[i][1] = "nothing";
}
}
void loop() {
//spiting the string into pairs of key=value
splitArray(myString);
//printing outside the split function, junk in array elemnts
printArray();
delay(5000);
}
void splitArray(String inStr) {
int i = inStr.length();
char inChar[i];
inStr.toCharArray(inChar, i);
char * buf;
int pos = 0;
buf = strtok(inChar, ";");
while(buf != NULL) {
splitThisPair(buf, pos);
buf = strtok(NULL, ";");
pos++;
}
//printing from within split unction, all looks good
printArray();
}
void splitThisPair(char * inChar, int pos){
char * saveptr;
char * buf1 = strtok_r(inChar, "=", &saveptr); // command
char * buf2 = strtok_r(NULL, "=", &saveptr); // value
ca[pos][0] = buf1;
ca[pos][1] = buf2;
}
void printArray() {
Serial.println("\n");
int i;
for (i = 0; i < 5; i++) {
Serial.print(i);
Serial.print(" -> ");
Serial.print(ca[i][0]);
Serial.print(" = ");
Serial.println(ca[i][1]);
}
}