如何从函数返回二维数组

问题描述 投票:0回答:10

我正在尝试使用以下代码从函数返回二维数组:

int **MakeGridOfCounts()
{
    int cGrid[6][6] = {{0, }, {0, }, {0, }, {0, }, {0, }, {0, }};
    return cGrid;
}
c++ arrays multidimensional-array
10个回答
63
投票

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

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

17
投票

使用指针到指针的更好替代方法是使用

std::vector
。它负责内存分配和释放的细节。

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

10
投票

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

std::vector
的文档。

在您的代码中,您可以使用

vector<vector<int> >
或者您可以使用 36 个元素
vector<int>
模拟二维数组。


7
投票

您正在(尝试)/在代码片段中执行的操作是从函数返回局部变量,这是完全不推荐的 - 根据标准也是不允许的。

如果你想从你的函数创建一个

int[6][6]
,你要么必须在自由存储上为其分配内存(即使用new T/malloc或类似函数),要么传入一个已经存在的分配一块内存给
MakeGridOfCounts


4
投票

该函数返回一个静态二维数组

const int N = 6;
int (*(MakeGridOfCounts)())[N] {
 static int cGrid[N][N] = {{0, }, {0, }, {0, }, {0, }, {0, }, {0, }};
 return cGrid;
}

int main() {
int (*arr)[N];
arr = MakeGridOfCounts();
}

您需要将数组设为静态,因为它将具有块作用域,当函数调用结束时,将创建并销毁数组。静态作用域变量持续到程序结束。


3
投票
#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 ; 
}

1
投票

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

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

    }

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

1
投票

我建议你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;
}

0
投票
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;
}

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.