aln447
aln447

Reputation: 1011

How to correctly pass an 2D array pointer as argument?

For the heads up: I am incredibly new with cpp. Being used to PHP and JS as work languages, I find pointers incredibly confusing.

So I have this Class called Macierz. The class is supposed to hold Matrixes of float variables and ought to have a constructor accepting an 2d array in order to print them into the field.

The field is declared like this float mx3[3][3];

And the constructor has such declaration: Macierz(float**); With the body using an additional function:

Macierz::Macierz(float** f) {
    length = 3;
    populateWith(f, length);
}

void Macierz::populateWith(float** val, int length) {
    for (int i = 0; i < length; i++)
        for (int j = 0; j < length; j++)
            mx3[i][j] = val[i][j];
}

In my main() function I want to declare the class with a created float array. I try to do it as so, but It just won't work the way God intended:

float y[3][3] = { {1.00f, 2.00f, 3.00f}, { 4.00f, 5.00f, 6.00f }, { 7.00f, 8.00f, 9.00f } };

Macierz m5(y);

This is the base template of what I want to do. I've tried making the y variable a double pointer, a regular pointer, passing via reference and it just won't kick.

What would be the most prober way to pass this variable?

Any help will be amazing, I am really a noob in this language.

Upvotes: 1

Views: 63

Answers (2)

aln447
aln447

Reputation: 1011

Managed to fix this by copying the float into a pointer-to-pointer types

float y[3][3] = { {1.00f, 2.00f, 3.00f}, { 4.00f, 5.00f, 6.00f }, { 7.00f, 8.00f, 9.00f } };

    float** x = 0;
    x = new float*[3];

    for (int i = 0; i < 3; i++) {
        x[i] = new float[3];

        for (int j = 0; j < 3; j++) {
            x[i][j] = y[i][j];
        }
    }

    Macierz m5(x);

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409472

You need to remember that arrays naturally decays to pointers to their first element. But that isn't recursive.

For y in your example, the decay is to a pointer to the first element of y, which is equal to &y[0]. That is a pointer to an array, and will have the type float(*)[3], which is the type you need for your arguments:

Macierz::Macierz(float (*f)[3]) { ... }

Upvotes: 1

Related Questions