从函数返回一个二维数组嗨,我是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 关注
- 721 浏览
添加回答
举报
0/150
提交
取消