I have the following structure:

struct inst_t {
    const char *s1;
    const char *s2;

I'd like to initialize a constant array of this structure like this where all the strings are PROGMEM'ed:

const char START[] PROGMEM = "START";
const char ATZ[] PROGMEM = "ATZ";
const char ATE0[] PROGMEM = "ATE0";
const char OK[] PROGMEM = "OK";

static inst_t insts[] = {
    { START,      NULL },
    { ATZ,        OK },
    { ATE0,       OK }

You can see there is a lot of duplication here though. Is there anyway way I can inline the PROGMEM strings directly into this array initialization without separately declaring each string as being in PROGMEM?


If the strings are similar size you can, like this:

const int NUMBER_OF_ELEMENTS = 10;

typedef struct {
   char description [12];
} descriptionType;

const descriptionType descriptions [NUMBER_OF_ELEMENTS] PROGMEM = { 
 { "Furnace on" }, 
 { "Furnace off" }, 
 { "Set clock" }, 
 { "Pump on" }, 
 { "Pump off" }, 
 { "Password:" }, 
 { "Accepted" }, 
 { "Rejected" }, 
 { "Fault" }, 
 { "Service rqd" }, 

void setup ()
  Serial.begin (115200);
  Serial.println ();

  for (int i = 0; i < NUMBER_OF_ELEMENTS; i++)
    // make a copy of the current one
    descriptionType oneItem;
    memcpy_P (&oneItem, &descriptions [i], sizeof oneItem);

    Serial.println (oneItem.description);
    }   // end of for loop

  }  // end of setup

void loop () { } 

This is a bit wasteful of program memory, because you need to allow for the largest string (your example had them all similar sizes) but what you save is not needing a two-byte pointer for each string, so if they are all similar lengths, it will take about the same memory.

See my page about PROGMEM.

Your Answer

