Getting an Array of data from spark :)

Never mind @Ric , it works with strdup.
But earlier, @ScruffR mentioned a danger of using this command...

Not sure what the risks for a project would be...

I don’t understand the nuances of these various functions well enough to know what the possible consequences of using strdup would be. If you’re starting with a const char*, and need to convert it to a char* to pass to strtok, then you could use strcpy or strncpy.

    const char *args = "hello,15,goodbye,3.14";
    int len = strlen(args) +  1;
    char theString[len];
    strcpy(theString, args);
    char* s = strtok(theString, ",");
    int second = atoi (strtok(NULL, ","));
    // etc.

That’s great @Ric ! No worries, we will see…

BTW, I have just posted 2 tutorials for the community with both methods.
Hopefully we will see some discussion about the merits of different ways.
I cannot thank you enough for your help!

For me this is going to work…

Greetz!

Just to throw in a new idea of how to parse a string with known format - have a look at sscanf()

Some background:
strtok() actually manipulates the source string by replacing each found delimiter with a '\0' string terminator, that’s why you can’t use a const char*.

strdup() allocates a chunk of RAM in the heap area to copy the source string to and when done will return (free) this space to the heap. But if in between allocating and freeing some other function (like constructing a String object) requires (allocates) some heap space that one chunk you are going to free can only ever be reused for other things the same size or smaller than your previous string (till the adjacent object gets freed too).
This is what heap fragmentation is. You might have kilo bytes of space available but only scattered about and no chunk big enough to take that one new string (or something else) that you want to allocate.
Errors (usually SOS errors on Particles) like this are hard to track since they usually only happen after a long time and then only under particular circumstances.

1 Like

Thanks for this clarification @ScruffR !
I certainly want to avoid SOS problems in my projects…

Obviously, I have a lot to learn about the differences between types of string variables and how to handle each of them. I’ll study this deeper and try to apply it where I can.

:wave:

1 Like