Reputation: 11
I have a char array char *menu_strings[8];
that I fill with the options for an on-screen menu dynamically in a reusable menu() function. I can change the items individually with hand-typed strings, e.g. menu_strings[0] = "New";
etc. but how do I take a char* returned from another function and insert it into one of the array's "strings"? If I try to loop through the array using the function with something like this:
for (i=0; i<8; i++)
{
char returnedOption[32];
if (getOption(i, returnedOption))
menu_strings[i] = returnedOption;
}
bool getOption(byte entryNum, char* option) { //code and stuff }
...all 8 menu_strings are filled with the eighth/last option returned (i=7) instead of each individual entry's string...
for (i=0; i<8; i++)
Serial.println(menu_strings[i]);
Outputs:
option eight
option eight
option eight
option eight
option eight
option eight
option eight
option eight
I'm using the arduino IDE but feel pretty confidently that I'd be screwing up the usage of pointers in any C/++/# here. Also, the returned char* is never more than 31 chars plus a null pointer.
Upvotes: 0
Views: 94
Reputation: 11
Many thanks to PaulMcKenzie, yardpenalty and deviantfan who led me to the answer:
Get out of the
char *
business and simply usestd::string
. You are also probably returning the address of a local array, given what you posted. If you are doing that, returning the address of a local variable is undefined behavior.
This led me to use the Arduino String object instead of char*
https://www.arduino.cc/en/Reference/StringObject
and use toCharArray()
for any library calls that insist on a char pointer. This works, but added around 2k (or 7% of my usable program memory!).
In the end, I ditched the * pointer as this is incorrect, and used strcpy
properly as recommended by deviantfan and yardpenalty to stay away from the String
library. Its liabilities are further extolled here: https://hackingmajenkoblog.wordpress.com/2016/02/04/the-evils-of-arduino-strings/
Upvotes: 1