简体   繁体   中英

C++ Inserting 2D array Object into another 2D array Object

In using Dev C++, I am trying to insert a smaller 2D array object into a larger 2D array object. While attempting to achieve that, I came into compilers errors which I do not know how to solve.

I attempt to insert the smaller Object by making it returning the array's name. Then I attempt to change the values inside the large array with the values of the smaller array.

There two line of code that I have problems with:

int result = smallerArray.extractPiece();
largerArray.extractArray(result);

And within these two lines of codes:

int Piece::extractPiece()
{
    return **pieceArray;
}

and

void Grid::extractArray( int** arr )
{
    for(int i = 0; i < xGrid ; ++i)
    {
         for (int j = 0; j < yGrid ; ++j)
         {
             squares[i][j] = arr[i][j];
                 }
    }
}

The two of the problems is that "int result" will not hold smallerArray.extractPiece(), and if i just put "smallerArray.extractPiece()" in largerArray.extractArray(), i still get problems. I attempted to make "int result" a pointer pointer, as "int** result", i still have the same errors.

These are the errors that i get when i try to compile in Dev C++:

In function `int main()';
invalid conversion from `int' to `int**'
initlizing argument 1 of 'void Grid::extractArray(int**)'
[Build Error] [grid test.o] Error 1

Does anyone know whats wrong?

It's precisely this bunch of code:

int result = smallerArray.extractPiece();
largerArray.extractArray(result);
// ...
int Piece::extractPiece() {
    return **pieceArray;
}

Trying to pass an int to extractArray, which wants a pointer to a pointer, presumable your dynamic array, and not an int. Try changing it to

int **result = smallerArray.extractPiece();
largerArray.extractArray(result);
// ...
int ** Piece::extractPiece() {
    return pieceArray;
}

Only changing result to a pointer to pointer won't work. You of course also have to change what extractPiece returns (changing from int to int**)

Look, always at least for me it was easier to manage 2D arrays internally as 1D arrays where M[i,j]=A[i*N+j] where N is the number of cols (or rows, if the 2D arrays is row-column type). Users may get elements with the i,j indices but my class always store A[M * N] as private data. Passing 1-D pointer arrays is easier than managing 2-D pointer arrays (you can't fall in the pointer-to-pointer syntax which can get messy in some code).,

This is not related to this question, but since I don't know about specific compiler optimization instrinsics, I wonder if M[i,j] gets transformed to A[i] internally to use simpler addressing modes in the generated code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM