// Forum: https://forum.arduino.cc/t/allocating-and-returning-an-array-of-structs-from-a-function/1261311/10
// Code by PieterP
// The ESP32 supports Serial.printf(), but then the variables
// have to match the %d, so I made them 'int'.
struct Person {
char const* name;
int age;
};
/*
template <class Callable>
void foreach_person(Callable callback) {
static constexpr Person persons[] {
{"John", 42},
{"Jill", 43},
};
for (const Person &person : persons) {
callback(person);
}
}
*/
// A test to change the records.
template <class Callable>
void foreach_person(Callable callback) {
Person persons[] = {
{"John", 0},
{"Jill", 0},
{"Josh", 0},
{"Jack", 0},
{"Jasmin", 0},
};
int record = 0;
for (Person &person : persons) {
person.age = random(0,128);
callback(record++,person);
}
}
void setup() {
Serial.begin(115200);
Serial.println();
int sum_of_ages = 0;
foreach_person([&](int r, Person p) {
Serial.printf("[%d] %s is %d years old\r\n", r, p.name, p.age);
sum_of_ages += p.age;
});
Serial.printf("Their combined age is %d\r\n", sum_of_ages);
}
void loop() {
delay(10);
}