elvaqueroloconivel1
elvaqueroloconivel1

Reputation: 919

Pass a matrix to a function

  unsigned char j[4][4];

And I want pass this element to the constructor of a class, I have a attribute in the class with the same type as the matrix

class x{

  private:

    unsigned char x[4][4];

  public:

     x(unsigned char j[4][4]);

};

I put values in my matrix j and in the constructor I want equalize j and x like this

x(unsigned char j[4][4]){
    x = j;
}

but and error appear in the code

incompatible types in assignment of ‘unsigned char (*)[4]’ to ‘unsigned char [4][4]’

why?

Upvotes: 3

Views: 329

Answers (2)

Nikos C.
Nikos C.

Reputation: 51840

You cannot pass arrays as arguments like this. You should not be using arrays to begin with. Really, just don't. The problem you're facing is just one problem out of a multitude of problems you will have when using arrays.

Instead, use an std::array that contains another std::array (so that it's two-dimensional):

#include <array>

class X {
private:
    std::array<std::array<unsigned char, 4>, 4> x;

public:
    X(std::array<std::array<unsigned char, 4>, 4> j);
};

In your constructor, just assign:

X(std::array<std::array<unsigned char, 4>, 4> j)
{
    x = j;
}

or, even better, use a constructor initialization list:

X(std::array<std::array<unsigned char, 4>, 4> j)
    : x(j)
{ }

(Also note that I changed your class name from x to X (capital.) Don't use conflicting names for classes and variables. It's confusing :-)

If you need your matrix to have a size that's determined at runtime instead of having a fixed size, then use std::vector instead of std::array.

Upvotes: 3

ForceBru
ForceBru

Reputation: 44838

You can't just assign arrays to each other: they're no vectors, which you can assign safely.

You'll have to iterate over that array passed as a parameter and copy its contents:

for(size_t i = 0; i < 4; ++i)
    for(size_t j = 0; j < 4; ++j)
        this->x[i][j] = argument_called_j[i][j];

BTW, to my mind, this x variable is a bit confusing because there's a class called x. If you'd like to take a look at how one could build such a class to work with matrices, check out my project called Matrix on GitHub.

Upvotes: 1

Related Questions