nghihoang2207
nghihoang2207

Reputation: 15

Having a bad output in Arduino program

i have a problem with this Arduino program Here is my code


char *stringsplit(char msg[])
 
{
  char *words[4];
   char * p;
  int i = 0;
   char dauphay[] = ",";
  p = strtok(msg, dauphay);
 while(p && i < 4)
  {
    words[i] = p;
    p = strtok(NULL, dauphay);
    ++i;
  }
  return *words;
}
void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  char msg[]="first,Second,third,four";
  char *p1=stringsplit(msg);
for(int i = 0; i < 4; i++)
  {
    Serial.println(p1[i]);
  }
}
void loop() {
  // put your main code here, to run repeatedly:

}

My expected output is "First Second Third Four" But my real output is "F i r s" What should i do to fix this problem

Upvotes: 1

Views: 57

Answers (1)

Olaf Dietsche
Olaf Dietsche

Reputation: 74078

In stringsplit(), you return *words. This is the same as

return words[0];

In other words, the returned pointer points to the first string, namely first. Then, the loop prints each element (character) in turn

f
i
r
s

To solve this, you must return the whole array, namely a pointer to words. This would change the signature and the return to

char **stringsplit(char msg[])
{
    // ...

    return words;
}

But this won't work either, because now stringsplit returns a pointer to a local variable.


There are a few ways to resolve this

  • make words static, e.g.

    static char *words[4];
    
  • or use dynamic memory allocation

    char **words = malloc(4 * sizeof(char*));
    
  • or pass the words array into stringsplit

    char **stringsplit(char msg[], char **words)
    {
        // ...
    }
    

    and then in setup()

    char *words[4];
    char **p1 = stringsplit(msg, words);
    

Each method has its pros and cons. In this small Arduino example (I'm no expert though), I would prefer the static variant, because it's quick and easy (some will say dirty ;-), even though the last method is the cleanest.


Looking at @Furkan's hint, doing the print inline seems the best solution. This also allows easily any number of sub-strings

char *p;
char dauphay[] = ",";
p = strtok(msg, dauphay);
while (p) {
    Serial.println(p);
    p = strtok(NULL, dauphay);
}

Upvotes: 2

Related Questions