Using PROGMEM in constructor Is it safe to use PROGMEM variable like dynamically allocated memory (a pointer to PROGMEM variable which is out of scope).

I need this so I can generate a variable size (before compilation), constant values, lookup array stored in flash.

Working example:

class Ex_class {
  public:
    Ex_class(int table_size, int value_range) {
      int flash_table[table_size + 1] PROGMEM;
      _ex_table = flash_table;
      for (int i = 0; i &lt;= table_size; i++) {
        _ex_table[i] = random(value_range);
      }
    }

    int get_value(int index) const { return _ex_table[index]; }

  private:
    int* _ex_table;
};

void setup() {
  randomSeed(analogRead(0));
  Serial.begin(9600);
  Ex_class ex_object(5, 50);
  for (int i = 0; i &lt;= 5; i++) {
    Serial.print(i); Serial.print(": "); Serial.println(ex_object.get_value(i));
  }
}

void loop() {}
The closest I could get to what you are trying to do is this:

template &lt;size_t table_size&gt; struct Ex_class {
  int get_value(int index) const {
    return pgm_read_word(&amp;_ex_table[index]);
  }
  int _ex_table[table_size];
};

void setup() {
  Serial.begin(9600);
  static PROGMEM const Ex_class&lt;5&gt; ex_object = {1, 2, 3, 4, 5};
  for (int i = 0; i &lt; 5; i++) {
    Serial.print(i);
    Serial.print(": ");
    Serial.println(ex_object.get_value(i));
  }
}

void loop() {}


avr-nm and avr-objdump confirmed that the object lives indeed in the
text section of the program. Please note that:


The object is PROGMEM const. It would make no sense to try to put in
PROGMEM anything that is not constant.
The object is allocated statically. It can be either a global or a
static local, but not an automatic local like in your example.
I am using aggregate initialization here. I know no other way to
statically initialize an array of variable length. If you have an
idea, I would be interested to know though.