Declare array size in constructor function

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:

#include <Library.h>
Library myObject(sizeOfArray)

on the library side, i've tried many solutions. the last one i did was:

Library::Library(int arraySize){
      array = new int[arraySize];
}

but it seems this is not the way to do it, so what should i do?

For this you need to use malloc and a pointer.

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));
    }
};

The other option is to use a static buffer. Simply pass a pointer (with the size).

Thanks for the answers. I cant test it right now, but i'll have a look

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;
};

Template:

MyObjTemplate< 20 > obj;

Static buffer:

int data[ 20 ];
MyObjStatic obj( data, 20 );