In the code below, the sprintf statement is not putting what I expect for the second and third replacements.
class Sensor {
protected:
static void formatString(char* result, char* type, uint32_t value);
private:
static unsigned long my_id;
};
unsigned long Sensor::my_id = 1; // i don't even know how the hell this works since it's private, but it does
void Sensor::formatString(char* result, char* type, uint32_t value) {
sprintf(result, "blah long string %d some more %s and then some more %lu", my_id, type, value);
// I tried changing my_id to Sensor::my_id in hopes that it would help, it didn't
}
I have an array of pointers to sub-classes of this class:
class Motion : public Sensor {
public:
void gimmeStuff(char* result) { Sensor::formatString(result, "motion", 42); }
}
class Light : public Sensor {
void gimmeStuff(char* result) { Sensor::formatString(result, "light", 42); }
}
Sensor* arr[2];
arr[0] = new Motion;
arr[1] = new Light;
I call it from the loop function like so:
void loop() {
for(int i = 0; i < 2; i++) {
char bob[100];
arr[i]->gimme_stuff(bob);
Serial.println(bob);
}
}
I end up with:
"blah long string 1 some more and then some more <crazy number that doesn't mean anything>"
If I put this in a loop, the <crazy number that doesn't mean anything> is the same for each
If I put in Serial.println statements for the two variables above the sprintf, the print out the correct values (so they are being passed in correctly).
It appears as though the fact that one of the variables passed as an argument to sprintf is static, and it is therefore choosing to believe the others ones are as well and pulling random values for them out of nowhere.
The standard g++ compiler on my mac does not appear to have this same issue.