gpt4 book ai didi

c++ - 从函数返回二维数组

转载 作者:IT老高 更新时间:2023-10-28 14:00:29 25 4
gpt4 key购买 nike

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

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

return cGrid;
}

最佳答案

此代码返回一个二维数组。

 #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 (int h = 0; h < height; h++) // loop variable wasn't declared
{
delete [] my2DArray[h];
}
delete [] my2DArray;
my2DArray = 0;
printf("Ready.\n");

return 0;
}

关于c++ - 从函数返回二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8617683/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com