Answers for "c++ function return 2d array"

C++
1

how to return 2d array from function c++

#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 array2Dn");
      printf("n");
    
      int height = 15;
      int width = 10;
      int** my2DArray = create2DArray(height, width);
      printf("Array sized [%i,%i] created.nn", 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;
    }
Posted by: Guest on June-03-2021
0

returning 2d array from function

#include <iostream>
#include <vector>
#include <iomanip>

using std::cout; using std::cin;
using std::endl; using std::string;
using std::vector; using std::setw;

constexpr int SIZE = 4;

int *ModifyArr(int arr[][SIZE], int len)
{
    for (int i = 0; i < len; ++i) {
        for (int j = 0; j < len; ++j) {
            arr[i][j] *= 2;
        }
    }
    return reinterpret_cast<int *>(arr);
}

int main(){
    int c_array[SIZE][SIZE] = {{ 1, 2, 3, 4 },
                               { 5, 6, 7, 8 },
                               { 9, 10, 11, 12 },
                               { 13, 14, 15, 16 }};

    cout << "input arrayn";
    for (auto & i : c_array) {
        cout << " [ ";
        for (int j : i) {
            cout << setw(2) << j << ", ";
        }
        cout << "]" << endl;
    }
    cout << endl;

    int *ptr = ModifyArr(c_array, SIZE);

    cout << "modified arrayn";
    for (int i = 0; i < SIZE; ++i) {
        cout << " [ ";
        for (int j = 0; j < SIZE; ++j) {
            cout << setw(2) << *(ptr + (i * SIZE) + j) << ", ";
        }
        cout << "]" << endl;
    }
    cout << endl;

    return EXIT_SUCCESS;
}
Posted by: Guest on November-06-2021

Browse Popular Code Answers by Language