从函数中返回一个二维数组

嗨,我是C ++的新手我想从一个函数返回一个二维数组。 这是这样的

int **MakeGridOfCounts(int Grid[][6]) { int cGrid[6][6] = {{0, }, {0, }, {0, }, {0, }, {0, }, {0, }}; return cGrid; } 

这段代码返回一个2d数组。

  #include <cstdio> // Returns a pointer to a newly created 2d array the array2D has size [height x width] int** create2DArray(unsigned height, unsigned width) { int** array2D = 0; array2D = new int*[height]; for (int h = 0; h < height; h++) { array2D[h] = new int[width]; for (int w = 0; w < width; w++) { // fill in some initial values // (filling in zeros would be more logic, but this is just for the example) array2D[h][w] = w + width * h; } } return array2D; } int main() { printf("Creating a 2D array2D\n"); printf("\n"); int height = 15; int width = 10; int** my2DArray = create2DArray(height, width); printf("Array sized [%i,%i] created.\n\n", height, width); // print contents of the array2D printf("Array contents: \n"); for (int h = 0; h < height; h++) { for (int w = 0; w < width; w++) { printf("%i,", my2DArray[h][w]); } printf("\n"); } // important: clean up memory printf("\n"); printf("Cleaning up memory...\n"); for ( h = 0; h < height; h++) { delete [] my2DArray[h]; } delete [] my2DArray; my2DArray = 0; printf("Ready.\n"); return 0; } 

你在做什么(试图做)/在你的代码片段中做的是从函数返回一个局部variables,这是不build议的 – 也不允许根据标准。

如果你想从你的函数中创build一个int[6][6] ,你将不得不在free-store上为它分配内存(即使用新的T / malloc或类似的函数),或者传入已经将内存分配给了MakeGridOfCounts

这段代码不会起作用,如果我们修复它,它不会帮助你学习正确的C ++。 如果你做一些不同的事情会更好。 原始数组(特别是multidimensional array)很难正确地传递到函数。 我想你会更好,从一个代表数组的对象开始,但可以安全地复制。 查找std::vector的文档。

在你的代码中,你可以使用vector<vector<int> >或者你可以用一个36元素的vector<int>来模拟一个2-D数组。

使用指针指针的一个更好的select是使用std::vector 。 这需要处理内存分配和释放的细节。

 std::vector<std::vector<int>> create2DArray(unsigned height, unsigned width) { return std::vector<std::vector<int>>(height, std:vector<int>(width, 0)); } 

无论你在函数中做了什么样的修改,都将会持续下去。所以不需要返回任何东西。你可以传递2d数组并且随时更改它。

  void MakeGridOfCounts(int Grid[][6]) { cGrid[6][6] = {{0, }, {0, }, {0, }, {0, }, {0, }, {0, }}; } 

要么

 void MakeGridOfCounts(int Grid[][6],int answerArray[][6]) { ....//do the changes in the array as you like they will reflect in main... } 

返回一个指向所有行起始元素的指针数组是返回2d数组唯一体面的方法。

 int** create2DArray(unsigned height, unsigned width) { int** array2D = 0; array2D = new int*[height]; for (int h = 0; h < height; h++) { array2D[h] = new int[width]; for (int w = 0; w < width; w++) { // fill in some initial values // (filling in zeros would be more logic, but this is just for the example) array2D[h][w] = w + width * h; } } return array2D; } int main () { printf("Creating a 2D array2D\n"); printf("\n"); int height = 15; int width = 10; int** my2DArray = create2DArray(height, width); printf("Array sized [%i,%i] created.\n\n", height, width); // print contents of the array2D printf("Array contents: \n"); for (int h = 0; h < height; h++) { for (int w = 0; w < width; w++) { printf("%i,", my2DArray[h][w]); } printf("\n"); } return 0; }