String myText vs char *myText

I have a function to which I would like to pass some text that will later be displayed on an LCD. I read that the implementation of String has bugs and should not be used. I have been able to pass some text using a char pointer, but I am concerned that I may be doing it wrong as the size is not predefined. The example below works fine to output each bit of text, but I am concerned that in a more complex program I would end up overwriting some memory somewhere due to the undefined variable sizes. Please could I have some suggestions regarding if I am using the pointer correctly.

void setup() {
  Serial.begin(9600);
}

void loop() {
  MyCharFunction("Example CHAR Text");
  MyStringFunction("Example STRING Text"); 
}

void MyCharFunction (char *myText) {
    Serial.println(myText);
}

void MyStringFunction (String myText) {
    Serial.println(myText);
}

What you have is mostly fine. But, because you're passing the address of string literals, you should use 'const' for the pointer.

void MyCharFunction (const char *myText) {
    Serial.println(myText);
}
1 Like

It's not a matter of "bugs". The "String" class handling requires almost continuous memory allocation/deallocation, ad small MCUs like Arduino don't have any kind of "garbage collector" so using and changing String objects bring to a potential excess of memory fragmentation, unless it either completely locks the program or at least start unpredictable behaviour.

Your example is not wrong, except for the fact you just pass a constant "C string", print it, and doing nothing more. You can obviously use C strings variables the same way, with MyCharFunction:

...
void loop() {
  MyCharFunction("Example CHAR Text");
  char message[16] = "Hello world!"; // here you can put any string up to 15 characters
  MyCharFunction(message);
}
...
1 Like

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.