I annotated the likely dynamic memory allocations with the String below.*** I am not sure what the GD stuff is doing under the hood. May be worth looking into.
void setup(){
}
void loop(){
// Allocate a string object on stack. Depending on implementation, this could be as small as
// a pointer to memory and a int tracking size.
// This will invoke assignment operator of string, which will likely cause a dynamic memory
// allocation here and then copy the null terminated string into that buffer, then set the pointer within
// the String object.
String temp = ââ;
// Another dynamic memory allocation here of the size of "Main Menu" + 1, then copy the string
/// into the buffer
temp = "Main Menu";
GD.cmd_text(240,150,OPT_CENTER, temp.c_str());
// yet one more here.
temp = "New Program";
GD.cmd_text(240,150,OPT_CENTER, temp.c_str());
etc.....
}
As for your second snippet. That is the right idea. You will need to put your char temp[50]
either in loop() or make it a global variable. Placing it within setup will cause it to be stack allocated and then go out of scope once the setup()
function finishes, making it not possible to access within the loop()
function.
However, if you are not doing any formatting of the strings, then I would suggest the following:
void setup(){
}
void loop(){
GD.cmd_text(240,150,OPT_CENTER, "Main Menu");
GD.cmd_text(240,150,OPT_CENTER, "New Program");
etc.....
}
The strings âMain Menuâ and âNew Programâ already live in a section of your binary called TEXT. What the above code does is just pass a pointer to these strings directly to the cmd_text
function without any copying or dynamic allocation.
If you need to do formatting, ie printf, then do something like this:
void loop(){
GD.cmd_text(240,150,OPT_CENTER, "Main Menu");
GD.cmd_text(240,150,OPT_CENTER, "New Program");
// Allocate 64 bytes on stack
char buffer[64];
// Format your message into that memory
snprintf(buffer, sizeof(buffer)/sizeof(buffer[0]), "Temperature1 %d", temperature1);
// Print it
GD.cmd_text(240, 150, OPT_CENTER, buffer);
// Reuse that stack memory
snprintf(buffer, sizeof(buffer)/sizeof(buffer[0]), "Temperature2 %d", temperature2);
GD.cmd_text(240, 150, OPT_CENTER, buffer);
etc.....
}
The above makes the allocations easy to see now. There is no abstraction around the character arrays and if we knew how cmd_text worked, we can fairly easily guesstimate how this function behaves from a memory standpoint.
*** String may also be implemented with a small string optimization where small strings are stored directly in the class instead of copied into a dynamically allocated buffer. Usually this is for strings less than 16 characters long.