I’ve got class similar to this:
class Krzyzowka
{
protected:
char model[40][40];
int x, y;
public:
Krzyzowka() { }
Krzyzowka(char model[][40], int x, int y)
{
this->model=model;
}
};
Now, I declare in main():
char array[10][10];
and want to pass it to the:
Krzyzowka(char model[][40], int x, int y)
I’m doing it this way:
Krzyzowka obj(array, 10, 10);
But then I want to set the model 2D array with the passed array:
this->model=model;
But compiler returns two errors:
error: no matching function for call to ‘Krzyzowka::Krzyzowka(char [10][10], int, int)’
error: incompatible types in assignment of ‘char (*)[40]’ to ‘char [40][40]’
How can I do this correctly? Thanks in advance for help.
There is no operation available that automatically assigns an array to another array.
Possible workarounds that come to mind:
Manually copy-assign the data to your internal array using a loop (make sure to keep track of the effective
nrowsandncols). For circumventing the compiler complaints you could use a template (assuming the size is known at compile time):Now you can create the object like:
If the dimensions of the array are only known at run time (e.g. based on user input, and
char** arraydynamically allocated by nestednew[]), you may need to adopt the approach given here or switch to the following.Even better would probably be to use some standard array type, like
std::vector(which you can swap or assign). Then you have no problem with the compiler type incompatility complaints either.