Hi all, newbie (in terms of programming C++) here.
For a project I have created an array of char arrays like this (trying to avoid the String object as vastly recommended in the forum):
char *MyArray[4] = {"str0", "str1", "str2"};
However, I have different states/user profiles that require "MyArray" to have completely different contents depending on a menu button press. I thought about doing something like:
char *MyArray[4]; //decare the array here
void onButtonPressSelectionFcn(uint8_t ProfileId) {
switch (ProfileId) {
case 0:
MyArray[4] = {"str0", "str1", "str2"}; // define the array
case 1:
MyArray[4] = {"str3", "str4", "str5"}; // depending on the user profile
}
This did not work because MyArray is an array of pointers to static strings, right?.
So my question: How do I assign new values to the global variable "MyArray" or what is the best way of achieving my goal that MyArray holds a different set of strings / char arrays depending on user input?
And, additional question, am I right in the understanding that I should try to store these arrays in the flash memory using PROGMEM to save space? I am using a pro micro with only 2.5 kbyte SRAM.
You can basically create your array for each profile and then just assign a pointer to whichever one you wish. You also have to declare them as constant.
marco_c:
That did not work because that's not how you assign pointers to the strings. This may work better
myArray[0] = "str0";
myArray[1] = "str1";
myArray[2] = "str2";
Well, I might be wrong, but the arduino ref says the way I did this in my code IS the correct way to create and array of char arrays. Also, your examble is not really feasible for the amount of strings I want to save (50 or more strings per profile at least). I should have mentioned that in the original post - sorry.
marco_c:
Also, why is myArray declared [4] when you only need [3]?
I thought that you have to increase the number by one as there needs to be space for the '\0' indicactor at the end of an array?
Just to understand the logic: The **MyArray is a pointer to an array of pointers to strings and in the onButtonPressSelectionFcn you just assign different of these arrays (MyArray1 or MyArray2) to it, right?
the way I did this in my code IS the correct way to create and array of char arrays
You may be confusing a static initializer with a run time assignment. This char *MyArray[4] = {"str0", "str1", "str2"};is a valid declaration with initializer, but thisMyArray[4] = {"str0", "str1", "str2"}; is not a valid assignment operation.
I thought that you have to increase the number by one as there needs to be space for the '\0' indicactor at the end of an array
Your array is an array of pointers (ie, memory addresses) so there is no sense in which you have a nul character at the end. The actual strings themselves need the nul character.