c++ - 如何重新分配三重指针

标签 c++ pointers

我目前正在为用C++实现的tictactoe的AI工作,目前我的进展正在进行中。在我的代码中,我有一个看起来像这样的结构。

struct Board {
    int config[3][3];
    Board ** nextboards;
};
我将nextboards设置为双指针,因为我想动态地将一个木板分配给未知数目的木板。使用指针数组将使我的存储不动态。为了增加可能的 Action ,我做了一个功能。
void addPossibleMoves(Board *** board, bool xplayer) {
    
    Board * newboard = (Board *)malloc(sizeof(Board));
    Board * another = (Board *)malloc(sizeof(Board));
    
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            newboard -> config[i][j] = compare[i][j];
        }
    }
    
    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            another -> config[i][j] = compare[i][j];
        }
    }

    Board ***temp = (Board ***)realloc(board, 2*sizeof(Board));
    temp = board; 
    **board = newboard;
    printBoard( **board);
}
在此函数中,我通过引用传入双指针以操纵内部数据。我的目标是重新分配两倍大小的**board并插入两个节点以测试其是否有效。但是,当代码运行realloc函数时,它将暂停并返回不为零的值。有人可以告诉我我在做什么错。
这是我的主要功能。
int main() {

   bool xplayer = true;
   Board * startboard = (Board *)malloc(sizeof(Board));

   for (int i = 0; i < 3; i++) {
       for (int j = 0; j < 3; j++) {
           startboard -> config[i][j] = compare[i][j];
       }
   }
   startboard -> nextboards = (Board **)malloc(sizeof(Board));

   addPossibleMoves( & startboard -> nextboards, xplayer);
   printBoard( *(startboard -> nextboards));
}
我目前正在使用devc++作为我的助手。

最佳答案

我按照我认为的样子重写了您的代码。我完全保留了您应该执行什么代码的逻辑。我还保留了您处理内存的低级malloc / realloc / free方法。我的代码仍然具有此三重指针***,向您展示如何使用它。同样,在使用free分配之后,您以后也忘记了malloc内存,您应该始终释放分配的那些指针!
在真正的C++代码中,您应该使用new / delete / delete[]代替malloc / free。我认为,即使使用new / delete也不是一个好习惯,最好使用已经为您完成所有内存管理的那些结构,例如std::vector,请参见我的第二个解决方案示例,而不是保持简单的指针和手动删除它们,最好使用std::shared_ptr这样的智能指针。
下面的第一个代码基本上是您的代码,但有所改进。
Try it online!

#include <cstdlib>
#include <cstdio>

struct Board {
    int config[3][3];
    Board ** nextboards;
};

void freeNextBoards(Board ** nextboards) {
    Board ** cur = nextboards;
    while (*cur) {
        freeNextBoards((*cur)->nextboards);
        ++cur;
    }
    nextboards[0] = 0;
}

void freeBoard(Board * board) {
    freeNextBoards(board->nextboards);
}

void resizeNextBoards(Board *** pnextboards, int cnt) {
    *pnextboards = (Board **)realloc(*pnextboards, cnt * sizeof(Board*));
}

Board * createBoard() {
    Board * board = (Board *)malloc(sizeof(Board));
    board->nextboards = (Board **)malloc(1 * sizeof(Board*));
    board->nextboards[0] = 0;
    return board;
}

void printRepStr(char const * s, int cnt = 1) {
    for (int j = 0; j < cnt; ++j)
        printf("%s", s);
}

void printBoard(Board * board, int indent = 0) {
    for (int i = 0; i < 3; ++i) {
        printRepStr(" ", indent);
        for (int j = 0; j < 3; ++j)
            printf("%02d ", board->config[i][j]);
        printf("\n");
    }
    
    printRepStr(" ", indent);
    printRepStr("-", 3 * 3 - 1);
    printf("\n");
    
    Board ** cur = board->nextboards;
    while (*cur) {
        printBoard(*cur, indent + 4);
        ++cur;
    }
}

void addPossibleMoves(Board *** pnextboards, bool xplayer) {
    Board * newboard = createBoard();
    Board * another = createBoard();

    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            newboard->config[i][j] = 2 * (i + j); // compare[i][j];
        }
    }

    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            another->config[i][j] = 3 * (i + j); // compare[i][j];
        }
    }

    freeNextBoards(*pnextboards);
    resizeNextBoards(pnextboards, 3);
    
    (*pnextboards)[0] = newboard;
    (*pnextboards)[1] = another;
    (*pnextboards)[2] = 0;
}

int main() {
    bool xplayer = true;
    Board * startboard = createBoard();

    for (int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            startboard->config[i][j] = 1 * (i + j); // compare[i][j];
        }
    }

    addPossibleMoves(&startboard->nextboards, xplayer);
    addPossibleMoves(&startboard->nextboards[0]->nextboards, xplayer);
    printBoard(startboard);
    freeBoard(startboard);

    return 0;
}
输出:
00 01 02 
01 02 03 
02 03 04 
--------
    00 02 04 
    02 04 06 
    04 06 08 
    --------
        00 02 04 
        02 04 06 
        04 06 08 
        --------
        00 03 06 
        03 06 09 
        06 09 12 
        --------
    00 03 06 
    03 06 09 
    06 09 12 
    --------
第二个代码下面是第一个代码的改进版本,现在代替了无处不在的指针,我使用std::vector来自动管理内存,对于config的普通2D数组,我使用std::array,将文本输出到控制台,我使用了std::cout,还用于捕获异常我使用了try / catchstd::exception
您可以看到,在下面的基于 vector 的代码中,您根本不需要对malloc / realloc / free进行任何工作,因为您始终可以忘记分配后释放某些内容,因此所有操作都是在 vector 代码内自动完成的。
Try it online!
#include <cstdlib>
#include <cstdio>
#include <vector>
#include <array>
#include <stdexcept>
#include <iostream>
#include <iomanip>
using namespace std;

struct Board {
    array<array<int, 3>, 3> config = {};
    vector<Board> nextboards;
};

void printRepStr(char const * s, size_t cnt = 1) {
    for (size_t j = 0; j < cnt; ++j)
        cout << s;
}

void printBoard(Board const & board, size_t indent = 0) {
    for (size_t i = 0; i < board.config.size(); ++i) {
        printRepStr(" ", indent);
        for (int j = 0; j < board.config[i].size(); ++j)
            cout << setfill(' ') << setw(2) << board.config[i][j] << " ";
        cout << endl;
    }
    
    printRepStr(" ", indent);
    printRepStr("-", board.config[0].size() * 3 - 1);
    cout << endl;

    for (auto const & cur: board.nextboards)
        printBoard(cur, indent + 4);
}

void addPossibleMoves(vector<Board> & pnextboards, bool xplayer) {
    Board newboard, another;

    for (size_t i = 0; i < newboard.config.size(); ++i)
        for (int j = 0; j < newboard.config[i].size(); ++j)
            newboard.config[i][j] = 2 * (i + j); // compare[i][j];

    for (size_t i = 0; i < another.config.size(); ++i)
        for (int j = 0; j < another.config[i].size(); ++j)
            another.config[i][j] = 3 * (i + j); // compare[i][j];

    pnextboards.resize(2);
    
    pnextboards[0] = newboard;
    pnextboards[1] = another;
}

int main() {
    try {
        bool xplayer = true;
        Board startboard;

        for (size_t i = 0; i < startboard.config.size(); ++i)
            for (size_t j = 0; j < startboard.config[i].size(); ++j)
                startboard.config[i][j] = 1 * (i + j); // compare[i][j];

        addPossibleMoves(startboard.nextboards, xplayer);
        addPossibleMoves(startboard.nextboards[0].nextboards, xplayer);
        printBoard(startboard);

        return 0;
    } catch (exception const & ex) {
        cout << "Exception: " << ex.what() << endl;
    } catch (...) {
        cout << "Unknown Exception!" << endl;
    }
}

关于c++ - 如何重新分配三重指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64691254/

相关文章:

c++ - 使用单个数字表示多个变量

c++ - 运行存储在 `std::wstring` 中的控制台命令

c++ - 将 char 数组转换为整数

c - 尽管分配了指针,但指针仍指向 Null

c - 使用指针交换 int 数组值

c++ - 在全屏 Win32 OpenGL 中处理最小化

c - 结构的指针符号是否具有访问元素的特定样式?

c++ - 指向函数的指针和指向 WINAPI 函数的指针有什么区别?

c++ - 从迭代器中的函数指针调用函数

c++ - 在 CameraCaptureUI 中限制 'change camera"按钮中的相机类型