Retourneer een 2d array van een functie

Hallo, ik ben een nieuweling in C++
Ik probeer een 2D-array van een functie te retourneren.
Het is zoiets als dit

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

Antwoord 1, autoriteit 100%

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

Antwoord 2, autoriteit 25%

Een beter alternatief voor het gebruik van pointers naar pointers is om std::vectorte gebruiken. Dat zorgt voor de details van geheugentoewijzing en deallocatie.

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

Antwoord 3, autoriteit 15%

Die code gaat niet werken, en het zal je niet helpen om de juiste C++ te leren als we het repareren. Het is beter als je iets anders doet. Onbewerkte arrays (vooral multidimensionale arrays) zijn moeilijk correct door te geven van en naar functies. Ik denk dat je veel beter af bent met een object dat een array vertegenwoordigtmaar veilig kan worden gekopieerd. Zoek de documentatie op voor std::vector.

In uw code kunt u vector<vector<int> >of u kunt een 2D-array simuleren met een vector<int>met 36 elementen.


Antwoord 4, autoriteit 13%

Wat u in uw fragment doet (probeert te doen) is het retourneren van een lokale variabele van de functie, wat helemaal niet wordt aanbevolen – en het is ook niet toegestaan volgens de standaard.

Als je een int[6][6]van je functie wilt maken, moet je er ofwel geheugen voor toewijzen in de free-store (d.w.z. met behulp van nieuwe T/mallocof vergelijkbare functie), of geef een reeds toegewezen stuk geheugen door aan MakeGridOfCounts.


Antwoord 5, autoriteit 4%

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

Antwoord 6, Autoriteit 4%

De functie retourneert een statisch 2D-array

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

U moet de array statisch maken, omdat het een blokkoper zal hebben, wanneer de functie belt, wordt de array gemaakt en vernietigd. Statische scope-variabelen duren tot het einde van het programma.


Antwoord 7, Autoriteit 2%

Welke wijzigingen u ook in functie zou maken, blijven bestaan. Dus het is niet nodig om iets terug te keren. U kunt 2D-array passeren en deze wijzigen wanneer u maar wilt.

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

of

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

Antwoord 8

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

Antwoord 9

Terugkerende een reeks aanwijzingen die wijzen naar uitgangselementen van alle rijen is de enige fatsoenlijke manier om 2D-array terug te keren.


Antwoord 10

Ik zou u verstrekken matrixbibliotheek als een open source tool voor C++, is het gebruik ervan als arrays in C++. Hier kunt u documentie .

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

Other episodes