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

别说谁变了你拦得住时间么 提交于 2019-12-24 20:09:44

问题


In using Dev C++, I a m 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 &lt xGrid ; ++i)
    {
         for (int j = 0; j &lt 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?


回答1:


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**)




回答2:


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.



来源:https://stackoverflow.com/questions/394763/c-inserting-2d-array-object-into-another-2d-array-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!