I understand the potential risks of using dynamic memory allocation so I try to stick to static memory or local memory wherever possible.
My question was with classes. Sometimes I need to declare the size of an array inside a class using the constructor, like this:
class foo {
public:
foo(uint8_t ArrSize) {
//it does not have to be static memory, Just local to the class.
//This is just the best example I could think of to express my problem/question
static byte Array[ArrSize]; // <<< Error, Needs Constant Value
_ArrPoint = Array;
}
private:
byte *_ArrPoint;
};
void setup() {
foo X(5);
}
void loop() {
}
But this does not work
Up until now I would solve the issue like this:
#define foo_ArrSize 5
class foo {
public:
foo() {}
private:
byte Array[foo_ArrSize];
};
void setup() {
foo X;
}
void loop() {
}
However, It becomes increasingly difficult, especially when you have all these definitions tucked away inside .h files. It becomes even more tricky when I want two objects of the same class with different array sizes, like this:
`#define foo_ArrSize 5
class foo {
public:
foo() {
Serial.println(sizeof(Array));
}
private:
byte Array[foo_ArrSize];
};
void setup() {
Serial.begin(115200);
foo X; //<< this one has array of 5
#undef foo_ArrSize
#define foo_ArrSize 3
foo Y; //<< this one still has array of 5, not 3
}
void loop() {
}`
The only other way I know to solve this problem is with Malloc, whic I really don't like.
I have been stuck with this problem for a long time and never knew how to ask about it. I'm sorry if this explanation is a little hard to follow, I have been struggling to find the correct way to ask about this problem
I'm wondering if it is even a possibility to solve the problem the way I'm thinking.
Idk, I have a bad feeling Dynamic Memory is the only way to solve the problem because of scope problems. I was hoping maybe there is at least a better way aside from #define all the time
Thank you for all your help all in advance