return *words;You are returning a pointer to data that is about to go out of scope. IOW the memory you are pointing to has already been released. You should have no expectations on what may be there.
If you want to modify a char* within a sub-function, you need to declare the (fixed size) char array in the main function and pass the pointer to that array as argument. Returning the pointer is then no longer required, the original pointer is still pointing to the same address.
You are returning a pointer to data that is about to go out of scope. IOW the memory you are pointing to has already been released. You should have no expectations on what may be there.
If you want to modify a char* within a sub-function, you need to declare the (fixed size) char array in the main function and pass the pointer to that array as argument. Returning the pointer is then no longer required, the original pointer is still pointing to the same address.
Can you give me the example code for your advice. I don't understand your idea. Thank you very much
There are 3 serious problems with "char *words[4]":
It is declared inside stringsplit(), so it is a part of the stack.
Stack may be used by other functions after returning from stringsplit().
the return of stringsplit() gives only one(!) pointer, not the array of pointers.
So it is the best idea, to declare the pointer array "words[4]" outside as global. Then both functions are more simple and will work.
My solution:
char *words[4];
void stringsplit(char msg[]) {
int i = 0;
char* p = strtok(msg, ",");
while (p)
{
words[i++] = p;
p = strtok(NULL, ",");
}
}
void setup() {
// put your setup code here, to run once:
Serial.begin(38400);
char msg[] = "first,Second,third,four";
stringsplit(msg);
for (int i = 0; i < 4; i++)
{
Serial.println(words[i]);
}
}
void loop() {
// put your main code here, to run repeatedly:
}
char **stringsplit(char msg[])
{
static char *words[4]; // Make it 'static' so it doesn't disappear.
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; // Return the address of the list of character pointers
}
void setup()
{
// put your setup code here, to run once:
Serial.begin(115200);
delay(200);
Serial.println();
char msg[] = "first,Second,third,four";
char **p1 = stringsplit(msg); // The address of the list is a pointer to a pointer to a character.
for (int i = 0; i < 4; i++)
{
Serial.println(p1[i]);
}
}
void loop()
{
// put your main code here, to run repeatedly:
}