3
  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?

elvaqueroloconivel1
  • 889
  • 2
  • 8
  • 11

2 Answers2

3

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.

Nikos C.
  • 50,738
  • 9
  • 71
  • 96
1

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.

ForceBru
  • 43,482
  • 10
  • 63
  • 98
  • 1
    If you're doing it C-style, then you may as well `memcpy(x,j,sizeof(x))` or `memcpy(x,j,sizeof(j))`. – barak manos Mar 28 '16 at 19:29
  • Traversing with for loops for primitive types would be foolish premature pessimization. Use `memcpy()`. – Rob K Mar 28 '16 at 20:24