c++ - 如何在 void 函数内正确动态分配二维数组?

标签 c++ arrays

我还是 C++ 新手,所以不要对我刻薄。我想知道如何在void函数中初始化二维数组。

这是我的示例代码,但它给了我有关访问冲突位置的异常:

#include "stdafx.h"

void matrixInit(char***);
void matrixDel(char**);

void main(void){
    char** game=0;
    matrixInit(&game);
    matrixDel(game);
    return;
}


void matrixInit(char*** matrix) {
    matrix = new char**[3];
    for (int i(0); i < 3; i++) {
        matrix[i] = new char*[3];
        for (int j(0); j < 3; j++)
            *matrix[i][j] = '0';
    }
    return;
}

void matrixDel(char** matrix) {
    for (int i(0); i < 3; i++)
        delete[] matrix[i];
    delete[] *matrix;
    return;
}

最佳答案

@fireant 寻求分配数组的帮助。经过一些研究和调试后,我弄清楚了一切。我希望这个解决方案能够帮助将来的人!

#include "stdafx.h"

using namespace std;

int** matrixInit(int, int);
void matrixInit(int***, int, int);
void matrixDel(int**, int);
void matrixFill(int**, int, int);
void matrixPrint(int**, int, int);


void main(void) {
    const int rows = 3, cols = 3;
    int** game;

    matrixInit(&game, rows, cols); //Void allocation
    //game = matrixInit(rows, cols);  //Alternative allocation

    matrixFill(game, rows, cols);
    matrixPrint(game, rows, cols);
    matrixDel(game, rows);
    cout << endl << "Passed!"; //<iostream> lib required
    _getch(); //<conio.h> lib required
    return;
}


//Dynamical array allocation void function
void matrixInit(int*** matrix, int nRow, int nColumn) {
    (*matrix) = new int*[nRow];
    for (int i(0); i < nRow; i++)
        (*matrix)[i] = new int[nColumn];
}


//Dynamical array allocation pointer return function
int** matrixInit(int nRow, int nColumn) {
    int** matrix = new int*[nRow];
    for (int i(0); i < nRow; i++)
        matrix[i] = new int[nColumn];

    return matrix;
}


//Dynamical array deallocation void function
void matrixDel(int** matrix, int nRow) {
    for (int i(0); i < nRow; i++)
        delete[] matrix[i];
    delete[] matrix;
}


//Fill array void function 
void matrixFill(int** matrix, int nRow, int nColumn) {
    for (int i(0); i < nRow; i++)
        for (int j(0); j < nColumn; j++)
            matrix[i][j] = (j + 1) + (i * nRow);
}


//Print array void function
void matrixPrint(int** matrix, int nRow, int nColumn) {
    for (int i(0); i < nRow; i++)
        for (int j(0); j < nColumn; j++)
            cout << "[" << i << "][" << j << "] = " << matrix[i][j] << endl;
}

关于c++ - 如何在 void 函数内正确动态分配二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33447479/

相关文章:

c++ - 增加访问量可能存在错误

arrays - 可以在 shell 中读取命令用于将字符串分配给数组并重置默认数组

javascript - 为什么 Array.concat 在连接 jQuery 对象的二元素和三元素数组时会生成三元素数组?

javascript - 在 Django 中将字符串转换为 Javascript 中的字典列表

c++ - 混淆 C++ prime 加上动态数组的例子

c++ - std::equal_to 是否保证默认调用 operator== ?

c++ - C/C++ 头文件和实现文件 : How do they work?

c++ - 从双端队列中删除某个位置的对象

c++ - 如何包含 glew32.dll 而不必将其放入系统根目录

Javascript 如何将项目推送到对象中