C++ 从函数返回一个二维数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8617683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:52:46  来源:igfitidea点击:

Return a 2d array from a function

c++multidimensional-array

提问by user1047092

Hi I am a newbie to C++ I am trying to return a 2d array from a function. It is something like this

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

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

  return cGrid;
}

回答by Software_Designer

This code returns a 2d array.

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

 #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;
    }

回答by R Sahu

A better alternative to using pointers to pointers is to use std::vector. That takes care of the details of memory allocation and deallocation.

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

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

回答by Michael Kristofik

That code isn't going to work, and it's not going to help you learn proper C++ if we fix it. It's better if you do something different. Raw arrays (especially multi-dimensional arrays) are difficult to pass correctly to and from functions. I think you'll be much better off starting with an object that represents an arraybut can be safely copied. Look up the documentation for std::vector.

那个代码不会工作,如果我们修复它,它也不会帮助你学习正确的 C++。如果你做一些不同的事情会更好。原始数组(尤其是多维数组)很难正确地传入和传出函数。我认为你最好从一个代表数组但可以安全复制的对象开始。查找文档std::vector.

In your code, you could use vector<vector<int> >or you could simulate a 2-D array with a 36-element vector<int>.

在您的代码中,您可以使用vector<vector<int> >或者您可以使用36-element 模拟二维数组vector<int>

回答by Filip Roséen - refp

What you are (trying to do)/doing in your snippet is to return a local variable from the function, which is not at all recommended - nor is it allowed according to the standard.

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

If you'd like to create a int[6][6]from your function you'll either have to allocate memory for it on the free-store (ie. using new T/mallocor similar function), or pass in an already allocated piece of memory to MakeGridOfCounts.

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

回答by ahmad

#include <iostream>
using namespace std ;

typedef int (*Type)[3][3] ;

Type Demo_function( Type ); //prototype

int main (){
    cout << "\t\t!!!!!Passing and returning 2D array from function!!!!!\n"

    int array[3][3] ;
    Type recieve , ptr = &array;
    recieve = Demo_function( ptr ) ;

    for ( int i = 0 ;  i < 3 ; i ++ ){
        for ( int j = 0 ; j < 3 ; j ++ ){
            cout <<  (*recieve)[i][j] << " " ;
        }
    cout << endl ; 
    }

return 0 ;
}


Type Demo_function( Type array ){/*function definition */

    cout << "Enter values : \n" ;
    for (int i =0 ;  i < 3 ; i ++)
        for ( int j = 0 ; j < 3 ; j ++ )
            cin >> (*array)[i][j] ;

    return array ; 
}

回答by Siba Prasad Tripathy

returning an array of pointers pointing to starting elements of all rows is the only decent way of returning 2d array.

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

回答by Amir Fo

I would suggest you Matrix libraryas an open source tool for c++, its usage is like arrays in c++. Here you can see documention.

我建议你使用Matrix 库作为 c++ 的开源工具,它的用法就像 c++ 中的数组。在这里你可以看到文档

Matrix funcionName(){

    Matrix<int> arr(2, 2);

    arr[0][0] = 5;
    arr[0][1] = 10;
    arr[1][0] = 0;
    arr[1][1] = 44;

    return arr;
}

回答by Nirav Patel

Whatever changes you would make in function will persist.So there is no need to return anything.You can pass 2d array and change it whenever you will like.

您在函数中所做的任何更改都将持续存在。因此无需返回任何内容。您可以传递二维数组并随时更改它。

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

    }

or

或者

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

回答by user3785412

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;
}