c++ - How properly dynamically allocate 2d array inside void function? -
i 'm still newbie in c++, don't mean me. know how initialize 2 dimentional array in void function.
this example code gives me exceptions access violation locations instead:
#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]; (int i(0); < 3; i++) { matrix[i] = new char*[3]; (int j(0); j < 3; j++) *matrix[i][j] = '0'; } return; } void matrixdel(char** matrix) { (int i(0); < 3; i++) delete[] matrix[i]; delete[] *matrix; return; }
props @fireant allocating array. after research , debugger plays, figure out. hope solution in future!
#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]; (int i(0); < nrow; i++) (*matrix)[i] = new int[ncolumn]; } //dynamical array allocation pointer return function int** matrixinit(int nrow, int ncolumn) { int** matrix = new int*[nrow]; (int i(0); < nrow; i++) matrix[i] = new int[ncolumn]; return matrix; } //dynamical array deallocation void function void matrixdel(int** matrix, int nrow) { (int i(0); < nrow; i++) delete[] matrix[i]; delete[] matrix; } //fill array void function void matrixfill(int** matrix, int nrow, int ncolumn) { (int i(0); < nrow; i++) (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) { (int i(0); < nrow; i++) (int j(0); j < ncolumn; j++) cout << "[" << << "][" << j << "] = " << matrix[i][j] << endl; }
Comments
Post a Comment