0
#include<bits/stdc++.h>
using namespace std;
class test
{
    int a, b;
    public:
    void intake(int x, int y)
    {
        a=x;
        b=y;
    }
    void print(int mat[a][b])
    {
        for (int i = 0; i < a; i++)
        {
            for (int j = 0; j < b; j++)
            {
                cout<<mat[i][j]<<" ";
            }
        }
    }
};
int main()
{
    int mat[3][2] = {{2,3},{4,5},{6,7}};
    test arr;
    arr.intake(3,2);
    arr.print(mat);
    return 0;
}

I was trying to pass the values of the 2-dimensional array as variable, I tried this using class but it retrieves the error "a nonstatic member reference must be relative to a specific object".

The above code is having error and I need help to solve it.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770

1 Answers1

1

void print(int mat[a][b]) is not a valid declaration, as a and b are instance members, not compile-time constants. You can't use them in this context.

You could make print() be a template method instead (in which case, you don't need intake() anymore, and you could even make print() be static), eg:

#include <iostream>
using namespace std;

class test
{
public:
    template <size_t A, size_t B>
    void print(int (&mat)[A][B])
    {
        for (int i = 0; i < A; ++i)
        {
            for (int j = 0; j < B; ++j)
            {
                cout << mat[i][j] << " ";
            }
            cout << endl;
        }
    }
};

int main()
{
    int mat[3][2] = {{2,3},{4,5},{6,7}};
    test arr;
    arr.print(mat);
    return 0;
}

Online Demo

Otherwise, if you want intake() to specify the bounds, you would have to do something more like this instead:

#include <iostream>
using namespace std;

class test
{
    int a, b;
public:
    void intake(int x, int y)
    {
        a = x;
        b = y;
    }

    void print(int *mat)
    {
        for (int i = 0; i < a; ++i)
        {
            for (int j = 0; j < b; ++j)
            {
                cout << mat[(b*i)+j] << " ";
            }
            cout << endl;
        }
    }
};

int main()
{
    int mat[3][2] = {{2,3},{4,5},{6,7}};
    test arr;
    arr.intake(3,2);
    arr.print(&mat[0][0]);
    return 0;
}

Online Demo

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770