0

I have a public class in which I create an array, this array takes its size from the constructor and needs to be used in other functions (including int main). Therefore the variable must be public. my code looks something along these lines:

class myclass {
    public:
    int parameter1;
    int parameter2;
    myclass(int p, int p2) {
        parameter1 = p;
        parameter2 = p2;
    }
    void makeArray() {
        int array[parameter1][parameter2]; //I want this array to be public as the next method needs access to it
    }
    void otherFunction() {
        array[1][2] = 5; //just an example of what i need to do
    }
}

2 Answers2

0

Look up how to use pointers and dynamic memory..

To do what you want would be something like:

class myclass {
    public:
    int parameter1;
    int parameter2;
    int **a;

    myclass(int p, int p2) {
        parameter1 = p;
        parameter2 = p2;
        a = nullptr;
    }

    ~myclass() {
        // TODO: delete "a"
    }

    void makeArray() {
        // TODO: delete "a" if it has already been allocated

        a = new *int[parameter1];
        for (int i = 0; i < parameter1; ++i) {
          a[i] = new int[parameter2];
        }
    }

    void otherFunction() {
        // TODO: check that "a" has already been allocated
        a[1][2] = 5; //just an example of what i need to do
    }
}

You could also allocate the array in the constructor since you have the necessary information being passed in already.

Buddy
  • 10,874
  • 5
  • 41
  • 58
  • 1
    Why suggest pointers and manual memory allocation? At least use a `std::vector>` so you don't have to deal with that headache. – NathanOliver Dec 02 '19 at 21:47
0

This is more optimized way to do the same thing:

class myclass {
    public:
    int parameter1;
    int parameter2;
    int *array;
    myclass(int p1, int p2) {
        parameter1 = p1;
        parameter2 = p2;
    }
    void makeArray() {
        array = new int[parameter1*parameter2];
    }
    void otherFunction() {
        // ary[i][j] is then rewritten as ary[i*sizeY+j]
        array[1*parameter2+2] = 5;
    }
};
int main()
{
    int sizeX = 5;
    int sizeY = 5;

    myclass m1(sizeX,sizeY);
    m1.makeArray();
    m1.otherFunction();
    cout << m1.array[1*sizeY+2] << endl;
    return 0;
}
Saksham Chaudhary
  • 519
  • 1
  • 4
  • 14