Multiple C strings in PROGMEM defined in a big string

I saw an old thread about strings in PROGMEM and one member wanted to save them many per line so to speak. Consensus then was "you can't" or "do it this way" and I thought "hang on!".

So this has yet to commented to gold so feel free to point that out IF you have specific questions about any lines.

Note the compactness of the PROGMEM initialization. The txt string could be 255 bytes long, the embedded strings can vary as to length and should I make a version where txt[] is arrayed?

[code]
// trying out words in blocks
// 9/10/26 GFS -- example code free to copy and use

#include <avr/pgmspace.h>
const byte PROGMEM txt[] = "ABC\0DEF\0GHI\0JKL\0MNO";
const byte werds = 5;
PGM_P const werd[ werds ] PROGMEM = 
{ txt, txt + 4, txt + 8, txt + 12, txt + 16 };
PGM_P flashPtr;  // pointer into PROGMEM


void printFlashString( PGM_P str )
{
  byte buf;
  byte idx = 0;
  while( buf = pgm_read_byte( str + idx++ ))
  {
    Serial.write( buf );
  }
}

void userEnter() // yes, it blocks in setup, runs once.
{
  while ( !Serial.available());
  while ( Serial.available())
  {
    Serial.read();
  }
}


void setup()
{
  Serial.begin( 115200 );
  Serial.println( "\n\nwords in blocks test -- press enter\n\n" );
//  Serial.print( (int) txt );
//  Serial.print( " : " );
//  Serial.print( pgm_read_word( werd ));
  Serial.println( "\n" );

  userEnter(); // blocking code in setup()
  for ( byte i = 0; i < 5; i++ )
  {
    printFlashString( (PGM_P)pgm_read_word( werd + i )); // pgm_read_word( werd[ i ] ) does not work
    Serial.println( );
  }
}

void loop() {
  // put your main code here, to run repeatedly:

}
[/code]

Can you post a link to the original topic as it would be useful to see the context

I do recall linking something and maybe that was it TBH.

Yup, the forum found it for me.

ShermanP

Feb 7

post #4

Thanks very much. But each string has to have it's own PROGMEM? I couldn't just add PROGMEM to the array I had originally, with the (char*) things?

Note the terminating zeros embedded in txt[] and not commas edited into zeros lets me put the pointers in PROGMEM instead of RAM or EEPROM.

That was my thread. If it matters, I ended up doing this:

const char menuText[][17] PROGMEM = {   // Menu options
  "SET DATE/TIME",                      // set RTC date and time
  "SET CHKIN HOURS",                    // set one to three daily checkin hours
  "AUTO ADJUST DST",                    // enable auto adjust for daylight saving
  "SET BUZZER TIME",                    // set alarm buzzer time if check-in missed
  "SET QUICK TRIES",                    // number of immediate tries to send PUSH
  "ONE-HOUR RETRIES",                   // number of retries on successive hours if PUSH still fails
  "SET WIFI & KEYS",                    // set WiFi and Pushover keys
  "TESTPUSH TO ME",                     // send test PUSH notification to my phone
  "TESTPUSH TO ALL",                    // send to group
  "TRIM RTC SPEED",                     // adjust RTC oscillation speed
  "COINCELL VOLTAGE",                   // check voltage of RTC backup coin cell
  "EXIT MENU"
};

// and then later:

lcd.print((__FlashStringHelper*)&menuText[menuIndex]);

That works

If flash is not so much constrained (often the case, RAM is often the issue) or if the strings have similar length I use a struct with a fix length array and store that in PROGMEM, this way no need for the secondary pointer array and the manual maintenance of the offsets if you change a text. It costs you possibly some unused bytes in flash but easier to maintain or extend.

Something like this (typed here from iPhone, untested)

struct Werd {
  char text[4]; // max string length (3 here) + 1 for trailing null
  // other stuff if needed 
};

const Werd werd[] PROGMEM = {
  { "ABC" },
  { "DEF" },
  { "GHI" },
  { "JKL" },
  { "MNO" }
};

constexpr byte werds = sizeof werd / sizeof *werd;

void setup() {
  Serial.begin( 115200 );
  for ( byte i = 0; i < werds; i++ ) {
    Serial.println( (const __FlashStringHelper*) werd[i].text );
  }
}

void loop() {}

For human interaction, where speed is less important, you can get away with all sorts of things by discarding the idea that your string terminator needs to be a null, and searching through a single bit array for the Nth terminator...

I made the example strings 3-char but be sure that the link array suits varying string lengths on purpose. With extra link arrays, not just different orders but sub-groups (synonyms, commands,...) be used to access the total list of possibly many multi-word strings.

I was seeing if I could get this far first, embedding nulls in PROGMEM lines.

You can make the strings a little more readable by taking advantage of the compiler concatenating adjacent quoted text. print() is capable of printing directly from PROGMEM if you cast the char pointer to __FlashStringHelper pointer.

// trying out words in blocks
// 9/10/26 GFS -- example code free to copy and use

const char PROGMEM txt[] =
  "ABC\0"
  "DEF\0"
  "GHI\0"
  "JKL\0"
  "MNO";
  
const byte werds = 5;
const char* const werd[ werds ] PROGMEM =
{ txt, txt + 4, txt + 8, txt + 12, txt + 16 };


void userEnter() // yes, it blocks in setup, runs once.
{
  while ( !Serial.available());
  while ( Serial.available())
  {
    Serial.read();
  }
}

void setup()
{
  Serial.begin( 115200 );
  Serial.println( "\n\nwords in blocks test -- press enter\n\n" );

  userEnter(); // blocking code in setup()
  for ( byte i = 0; i < 5; i++ )
  {
    Serial.print((const __FlashStringHelper*)pgm_read_word(&werd[i]));
    Serial.println( );
  }
}

void loop() {
}

Note that you can directly index into werd[] when reading from PROGMEM, you just need to take the address of werd[i], not its content.

I have used a somewhat more convoluted method to get the compiler to calculate the addresses, looks like a lot of extra typing, but some creative use of a good text editor makes it quite easy regardless of the number of strings.

#define text_0  "ABC"
#define text_1  "DEF"
#define text_2  "GHI"
#define text_3  "JKL"
#define text_4  "MNO";

#define nul "\0"

const char PROGMEM txt[] =
  text_0 nul
  text_1 nul
  text_2 nul
  text_3 nul
  text_4
;

const char* const werd[] PROGMEM = {
  txt,
  werd[0] + sizeof(text_0),
  werd[1] + sizeof(text_1),
  werd[2] + sizeof(text_2),
  werd[3] + sizeof(text_3)
};

Thinking about it a bit, there really is no reason to go to all this trouble when making an array of pointers, because it takes the same amount of space as individually defining each string as a separate char array. There are only a couple of times I've done a single array with multiple strings, one was where the UNO did not have enough memory for the array of pointers, and the other was when using upper flash memory on a Mega, because the compiler cannot calculate the addresses for the pointer array at compile time.

making the nulls redundant and completely missing my point....

and at some point willya look into the code of that flashStringHelper (that I forget the Exact Syntax so I wrote the equivalent) and show me how much better it is?

and your +sizeof() trick does handle the simplified example but screws the use of indexes into variable length strings that didn't I post are there for that exact reason, substrings of different lengths allowed.

I don't know why I would #define the data and then pack those into an array that adds a null to "c strings" that already HAVE nulls.

Nice shot at missing my point. Just say it's lousy without coding something less please?

And then needing to use those string names to refer to the stored strings? Duhhhh, dat's why I put in the links and also causea dat ability to store and print variable length strings as stated yet ignored.

Tell me what else I didn't do like make separate char array strings since I put them all into one string and used the links to address those making it possible to have variable length strings just to play that song "onnnnnne moorree tiiiiiiime!".

I made an extra simple example. Now I regret that.

[code]
// trying out variable length words in blocks
// 9/11/26 GFS

#include <avr/pgmspace.h>
const byte PROGMEM txt[] = "how\0ya\0like\0me\0now?";
const byte werds = 5;
PGM_P const werd[ werds ] PROGMEM = 
{ txt, txt + 4, txt + 7, txt + 12, txt + 15 };
PGM_P flashPtr;  // pointer into PROGMEM


void printFlashString( PGM_P str )
{
  byte buf;
  byte idx = 0;
  while( buf = pgm_read_byte( str + idx++ ))
  {
    Serial.write( buf );
  }
}

void userEnter()
{
  while ( !Serial.available());
  while ( Serial.available())
  {
    Serial.read();
  }
}


void setup()
{
  Serial.begin( 115200 );
  Serial.println( "\n\nwords in blocks test -- press enter\n\n" );
  Serial.println( "\n" );

  userEnter(); // blocking code in setup()
  for ( byte i = 0; i < 5; i++ )
  {
    printFlashString( (PGM_P)pgm_read_word( werd + i )); // pgm_read_word( werd[ i ] ) does not work
    Serial.println( );
  }
}

void loop() {
  // put your main code here, to run repeatedly:

}
[/code]

I’m not getting your point here

The way this is written helps with readability and leads to exactly the same char buffer as you had.

Said plainly

Is exactly the same as

And has the advantage of readability and proper type..

Care to add some color ?


Yeah - sur it works but if you add 1 char to the one of the string you have to go and manually edit and figure out all the offsets in the pointer array.

My point is that if flash memory is not an issue - and very often it’s not - then losing a few bytes by having fixed length cStrings is not so much of an issue and saves you the trouble of maintaining the offsets or creating that array (which eats up flash too).

Using a struct lets you also store more information in a structured way if needed so this is extensible easily.

If that would amount to much work including debug, I write code to generate a correct list and pointers like I did for the word matches and still think about an easier, cleaner way.

I like the packed string for compactness but I only did it because a member wanted to know if it could be done. Answer is yes.

understood.

Any reason why you don't like it written like this ? too long?

const char PROGMEM txt[] =
  "ABC\0"
  "DEF\0"
  "GHI\0"
  "JKL\0"
  "MNO";

More like too tall but again, a member wanted to know if text words can be packed into a single PROGMEM string.

Not "the best" but to me has some charm and yes it's possible.

I wrote code to generate source for PROGMEM string arrays and supporting data since around 2016 if not before. Lists with lots and lots of words get "very tall". I'd rather pre-generate block data and shove that into flash. If I keep going, I might some day and hide it in a dot h or something. I'm look at lists in the 2000 to 3000 words length, longer for bigger than 328P MCU's. Things to encode novels.

it is a single text string was my point. notice there is no comma, it's not an array of cStrings. it's just taking advantage of the compiler concatenation feature. You can write "Hello" " world" or "Hello world" and it's the same for the compiler.

Would be useful if the array of pointers to the starts of the PROGMEM strings would be created automatically. And adding an 'anchor' at the end so it also can count the entries.

Then I only need to "worry" about the right text.

Not quite, you omitted the space between the words.

The whole point of the sizeof() was that the compiler calculates the offsets.

The defines do not create a null at the end, they just substitute the quoted text into the code wherever the defined reference is used. I omitted the null from the string for both readability and so that sizeof() would give the correct size.

As I said, I've used a single c-string for multiple strings in the past, but omitted the table of pointers because it was easy enough to go through the c-string and count the nulls to find a particular string, and the code did not require the speed of the pointer table. That code had a bit over 500 strings in total, of vastly varying length.

Indeed - corrected
Thx