Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ / Arduino: dynamic int array

I'm writing a class for the Arduino. It's been going well so far, but I'm sort of stuck now...

I have declared an int array in my class

class myClass
{
  public: MyClass(int size);
  private:
    int _intArray[];
};

When I initialize the class MyClass myClass1(5) I need the array to look like this {0,0,0,0,0}.

My question: what do I need to do so that the array contains 'size' amount of zeros?

MyClass::MyClass(int size)
{
    //what goes here to dynamically initialize the array
    for(int i=0; i < size; i++) _intArray[i] = 0;
}

Edit: Following up on various replies below, Arduino does not include the standard library so unfortunately std::vector is not an option

like image 594
JNK Avatar asked Feb 26 '23 16:02

JNK


2 Answers

Your code as I'm writing this:

class myClass
{
  public: MyClass(int size);
  private:
    int _intArray[];
};

The declaration of _intArray is not valid C++: a raw array needs to have a size specified at compile time.

You can instead instead use a std::vector:

class myClass
{
public:
    MyClass( int size )
        : intArray_( size )    // Vector of given size with zero-valued elements.
    {}

private:
    std::vector<int> intArray_;
};

Note 1: some compilers may allow your original code as a language extension, in order to support the "struct hack" (that's a C technique that's not necessary in C++).

Note 2: I've changed the name of your member. Generally underscores at the start of names can be problematic because they may conflict with names from the C++ implementation.

Cheers & hth.,

like image 68
Cheers and hth. - Alf Avatar answered Mar 04 '23 23:03

Cheers and hth. - Alf


You should use a std::vector.

class myCLass {
public:
    myClass(int size)
        : intarray(size) {
    for(int i = 0; i < size; i++) intarray[i] = 0;
    }
private:
    std::vector<int> intarray;
};
like image 43
Puppy Avatar answered Mar 04 '23 23:03

Puppy