Creation and referencing an array of message strings

Hello Everyone,

I would like to create a collection of messages that my program can access during run-time. I was thinking that I could create an array of strings like this:

String myMessages[] = {"Read an article", "Take Sam to the park (again)", "Listen to a podcast", "Write a couple of pages", "Start a new picture"};

I would then access it like this:

randIndex = random(sizeof(myMessages));
Serial.println(myMessages[randIndex]);

hoping that the serial terminal shows one of my strings out of the array.

Although, this is not necessarily working. I am getting sometimes legible output, sometimes gibberish. I suspect that the arrays are not referenced in the same way that, say, a Python list would be (this is what I am looking for, but i haven't found the right syntax yet):

>> print myMessages[2]
Listen to a podcast

Is there a way to easily do this in Arduino? I basically want to display one of my strings when this particular function is called.

*during debugging, I see that sizeof(myMessages) = 35

Rather than using the String class, I suggest you just use plain old c-strings:

char *myMessages[] = {"Read an article", "Take Sam to the park (again)", "Listen to a podcast", "Write a couple of pages", "Start a new picture"};

You code to access an element in the array is correct, but your calculation of the array size is not. The sizeof operator gives you the size of the array in bytes. To know the number of elements in the array, you need to divide that by the size of a single element:

int MESSAGE_COUNT = sizeof(myMessages) / sizeof(myMessages[0]);

First, don't use String, use char *, and make it PROGMEM to boot.

Secondly, you need to understand how sizeof() works. It returns the total amount of underlying memory consumed DIRECTLY by the array, which is the number of elements multiplied by the size of each element - which I think you'll find is 7 bytes in this case (the base size of a String object less any dynamically allocated memory).

To get the correct value out of sizeof() you should divide it by the size of a single element:

sizeof(myMessages) / sizeof(String)

majenko:
To get the correct value out of sizeof() you should divide it by the size of a single element:

sizeof(myMessages) / sizeof(String)

I would prefer to divide by the size of an actual element rather than the type, to avoid the possibility of a mismatch (as would occur here if the author took your advice to declare the array using c-strings).

PeterH:

majenko:
To get the correct value out of sizeof() you should divide it by the size of a single element:

sizeof(myMessages) / sizeof(String)

I would prefer to divide by the size of an actual element rather than the type, to avoid the possibility of a mismatch (as would occur here if the author took your advice to declare the array using c-strings).

That's very true, I'll give you that one :wink: