从函数返回一个二维数组

use*_*092 45 c++ multidimensional-array

嗨,我是C++的新手,我试图从一个函数返回一个二维数组.就是这样的

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

  return cGrid;
}
Run Code Online (Sandbox Code Playgroud)

Sof*_*ner 41

此代码返回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;
    }
Run Code Online (Sandbox Code Playgroud)


R S*_*ahu 13

使用指向指针的指针的更好替代方法是使用std::vector. 这会处理内存分配和释放的细节。

std::vector<std::vector<int>> create2DArray(unsigned height, unsigned width)
{
   return std::vector<std::vector<int>>(height, std::vector<int>(width, 0));
}
Run Code Online (Sandbox Code Playgroud)


Fil*_*efp 7

您正在(尝试做)/在您的代码段中做的是从函数返回一个局部变量,这根本不是推荐的 - 根据标准也不允许。

如果你想int[6][6]从你的函数中创建一个,你要么必须在自由存储上为它分配内存(即使用新的 T/malloc或类似的函数),要么将已经分配的内存块传递给MakeGridOfCounts.

  • @DeadMG ...如果他分配内存,他应该“删除”它。我不在乎你是否热衷于资源管理类,分配之后应该是解除分配。 (2认同)

Mic*_*fik 5

该代码行不通,并且如果我们对其进行修复,也不会帮助您学习正确的C ++。最好做一些不同的事情。原始数组(尤其是多维数组)很难正确地传递到函数或从函数传递。我认为从代表数组但可以安全复制的对象开始会更好。查找有关的文档std::vector

在您的代码中,可以使用vector<vector<int> >或者可以模拟具有36个元素的二维数组vector<int>