如何通过双指针将二维数组作为只读函数传递给函数

How to pass 2D array as read only to function by double pointer?

本文关键字:函数 只读 何通过 指针 二维数组      更新时间:2023-10-16

我需要传递指向2D数组的第一个元素的双指针,以防止函数修改2D数组中的任何元素。我想我可以用const引用-int** const &board来完成它,但它并没有像我预期的那样工作。此外,2D数组不能声明为const,因为它应该在该函数之外可以修改。这种功能是如何实现的?以下是我使用的工作简化代码:

#include <iostream>
class player
{
public:
    player(){}
                                 // returns player move
    int move(int** const &board)
    {
        board[1][1] = 9; // should be illegal
        return 9;
    }
};
class game
{
    int** board;    
    player *white, *black;
public:
    game(player* player1, player* player2): white(player1), black(player2)
    {
        int i, j;
        board = new int* [8];
        for(i = 0; i < 8; i++)
        {
            board[i] = new int [8];
            for(j = 0; j < 8; j++)
                board[i][j] = 0;
        }
    }
                // gets moves from players and executes them
    void play() 
    {
        int move = white->move(board);
        board[2][2] = move; // should be legal
    }
                 // prints board to stdout
    void print() 
    {
        int i, j;
        for(i = 0; i < 8; i++)
        {
            for(j = 0; j < 8; j++)
                std::cout << board[i][j] << " ";
            std::cout << std::endl;
        }
    }
};
int main()
{
    game g(new player(), new player());
    g.play();
    g.print();
}

我看到了你的代码,有趣的部分是:

int move(int** const &board)
{
    board[1][1] = 9; // should be illegal
    return 9;
}

如果您希望board[1][1] = 9是非法的,那么您必须将参数声明为:

int move(int const** &board);
//int move(int** const &board); doesn't do what you want

有一个区别:int** const不会使数据只读。请参阅第二个链接中的错误:

  • http://www.ideone.com/mnKc9(演示int** const(
  • http://www.ideone.com/BOvUL(演示int const**(

如果你把参数写成:会更好

int move(int const* const * const &board);

因为这使得一切都变得异常:所有以下赋值都将是非法的:

board[1][1] = 9;  //illegal
board[0] = 0;     //illegal
board = 0;        //illegal

请在此处查看错误:http://www.ideone.com/mVsSL

现在一些图表:

int const* const * const
    ^       ^       ^
    |       |       |
    |       |       |
    |       |       this makes board = 0 illegal
    |        this makes board[0] = 0 illegal
    this makes board[1][1] = 9 illegal
void f(const int* const* arr)
{
    int y = arr[0][1];
    // arr[0][1] = 10; // compile error
    // arr[0] = 0; // compile error 
}
void g()
{
    int** arr;
    arr[0][1] = 10; // compiles
    f(arr);
}

没有强制转换或复制必要的