You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++类内如何通过指针访问二维数组?访问输出异常问题求解

问题核心原因

你遇到的是悬挂指针引发的未定义行为:
构造函数内定义的char board[6][7]是栈上的局部变量,仅在构造函数执行的代码块内有效。构造函数运行结束后,这块栈内存会被系统自动回收,你存在成员变量boardPtr里的地址就变成了指向无效内存的野指针,后续通过这个指针赋值、读取的操作都是未定义行为,自然会出现乱码、打印出类似地址的异常结果。

修复方案

方案1(最推荐):直接将二维数组作为类成员

不需要额外用指针包装,类成员数组的生命周期和类实例完全绑定,不会出现提前释放的问题,也不需要手动管理内存:

class ConnectFour {
private:
    char board[6][7];
    static int player;
public:
    ConnectFour();
    void clearBoard();
    void printBoard();
    // 需要返回数组时可以直接返回指向数组首行的指针
    char (*getBoard())[7] {
        return board;
    }
};

ConnectFour::ConnectFour() {
    cout << " in constructor" << endl;
    clearBoard();
}

void ConnectFour::clearBoard() {
    for (int i = 0; i < 6; i++) {
        for (int j = 0; j < 7; j++) {
            board[i][j] = '-';
        }
    }
}

void ConnectFour::printBoard() {
    cout << "0 1 2 3 4 5 6" << endl;
    for (int i = 0; i < 6; i++) {
        for (int j = 0; j < 7; j++) {
            cout << board[i][j] << " ";
        }
        cout << endl;
    }
}

外部拿到getBoard()返回的指针后,可以直接通过ptr[i][j]的方式访问数组元素。

方案2:动态分配堆内存持有数组

如果你确实需要用指针的形式存储数组,可以在堆上分配内存,生命周期由你手动控制:

class ConnectFour {
private:
    char(*boardPtr)[6][7];
    static int player;
public:
    ConnectFour();
    ~ConnectFour(); // 必须添加析构函数释放内存
    void clearBoard();
    void printBoard();
};

ConnectFour::ConnectFour() {
    boardPtr = new char[6][7]; // 堆上分配内存,不会随构造函数结束自动释放
    cout << " in constructor" << endl;
    clearBoard();
}

// 析构函数释放堆内存,避免内存泄漏
ConnectFour::~ConnectFour() {
    delete[] boardPtr;
}

void ConnectFour::clearBoard() {
    for (int i = 0; i < 6; i++) {
        for (int j = 0; j < 7; j++) {
            (*boardPtr)[i][j] = '-';
        }
    }
}

void ConnectFour::printBoard() {
    cout << "0 1 2 3 4 5 6" << endl;
    for (int i = 0; i < 6; i++) {
        for (int j = 0; j < 7; j++) {
            cout << (*boardPtr)[i][j] << " ";
        }
        cout << endl;
    }
}

内容的提问来源于stack exchange,提问作者PurplePanda27

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 18:06:03