HI.
I'm trying to create a library, containing an array. I want the user to be able to determine the size of the array when he declares the object like this:
Yes, I know we say malloc() is bad, but that's not strictly true. malloc() and free() used repeatedly is bad, but a single malloc() in a constructor is fine.
class Foo {
private:
int *_array;
public:
Foo(int size) {
_array = (int *)malloc(size * sizeof(int));
}
};
If the number is a constant ( the user value ), i.e, not generated from something like serial input / random() / analogRead(), .... ThenI would stay away from dynamic memory.
Go with the static buffer option, or use a template.
template< unsigned N >
struct MyObjTemplate{
int Array[ N ];
};
struct MyObjStatic{
MyObjStatic( int *data, int count ) : data( data ), count( count ) {}
int *data;
int count;
};