E.Monogarov E.Monogarov - 2 months ago 7
C++ Question

passing array of int to constructor by reference

I'm working on program for AVR using c++

To use less memory I want to pass pointer to predefined array of int thru constructor to class member, to access array using OOP

I can't define this array in constructor, because it's a lib class and this array and its size will be changed in other programs using this lib class

Code:

class A
{
private:
const unsigned char arr[];
unsigned char arrSize;
public:
A(const unsigned char arr[],unsigned char arrSize)
{
this->arr = arr;
this->arrSize=arrSize;
}
};


Got next error on compilation:


incompatible types in assignment of 'unsigned char*' to 'unsigned char [0]


I understand that i did somthing wrong, but i can't realize what exactly wrong and how to fix it.

Answer

From the comments you say you just need a pointer to the array. To do that you just need a pointer in your class. It should look something like

class A
{
    private:
        const unsigned char* arr; // just use a pointer here
        unsigned char arrSize;
    public:
        A(const unsigned char arr[],unsigned char arrSize) : arr(arr), arrSize(arrSize) {}
        //                    ^^^^^ this decays to a const unsigned char*
};

I will caution you that this design can be problematic. If the class object outlives the array it points to and you use the pointer then you have undefined behavior as you no longer know what is in that space anymore.

Comments