문제

I've created an 2D array in C++ like this:

Board::Board(int rows, int cols){
    places = new int*[rows];
    for (int row = 0; row < rows; row++){
        places[row] = new int[cols];
        for (int col = 0; col < cols; col++){
            places[row][col] = 0;
        }
    }
}

And that works pretty well. Yet now i want to make a function which needs the length of the rows and columns of the array. I've tried a bit with the function:

sizeof()

But i only got it working with a normal array to return the length.

How to do this without declaring global variables for rows and cols?

도움이 되었습니까?

해결책

First of all, allocating the 2D array explicitly like this is not a good idea in terms of performance, since the memory is not contiguous. It's better to allocate it in one chunk of memory (unless it is too big), and abstract the 2D access, like most image processing libraries do (e.g. OpenCV).

That said, you should wrap this in a class that knows the size of the allocations, and then report the size with public methods.

다른 팁

it looks like you have a "Board" object, so store "place" and its size info into that class/struct

and create a sizeof() function that return an std::pair like :

  std::pair<unsigned int, unsigned int> sizeof(const Board& b)
  { return make_pair(b.row(), b.col());}

After creating a 2D-array in this way, places actually is a pointer pointing to the first row of its content.

Pointers don't store any metadata to indicate the size of the area they point to; if all you have is the pointer, then there's no (portable) way to retrieve the number of rows or columns in the array.

You will either need to pass that information along with the pointer, or you will need to use a sentinel value in the array itself (similar to how C strings use a 0 terminator, although that only gives you the logical size of the string, which may be smaller than the physical size of the array it occupies).

Check out How to get size of 2D array pointed by a double pointer? for more info.


Edit: I will recommend you to use vector<vector<int>> instead since you are using C++.

Following may help:

class Board
{
public:
    Board(int rows, int cols) : rowCount(rows), columnCount(cols) {
        places = new int*[rows];
        for (int row = 0; row < rows; row++){
            places[row] = new int[cols];
            for (int col = 0; col < cols; col++){
                places[row][col] = 0;
            }
        }
    }
private:
    int** places;
    int rowCount;
    int columnCount;
};

The information about size is stored is the instance itself.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top