從函數返回一個二維數組嗨,我是C ++的新手,我試圖從一個函數返回一個二維數組。就是這樣的int **MakeGridOfCounts(int Grid[][6]){
int cGrid[6][6] = {{0, }, {0, }, {0, }, {0, }, {0, }, {0, }};
return cGrid;}
3 回答

神不在的星期二
TA貢獻1963條經驗 獲得超6個贊
此代碼返回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; }

拉丁的傳說
TA貢獻1789條經驗 獲得超8個贊
該代碼不起作用,如果我們修復它,它不會幫助你學習正確的C ++。如果你做了不同的事情,那就更好了。原始數組(尤其是多維數組)很難正確地傳遞到函數和從函數傳遞。我認為從一個代表數組但可以安全復制的對象開始,你會好得多。查找文檔std::vector
。
在您的代碼中,您可以使用vector<vector<int> >
或者您可以使用36個元素模擬二維數組vector<int>
。

慕標琳琳
TA貢獻1830條經驗 獲得超9個贊
使用指針的更好的替代方法是使用指針std::vector
。這會處理內存分配和釋放的細節。
std::vector<std::vector<int>> create2DArray(unsigned height, unsigned width){ return std::vector<std::vector<int>>(height, std::vector<int>(width, 0));}
- 3 回答
- 0 關注
- 765 瀏覽
添加回答
舉報
0/150
提交
取消