Search
 
SCRIPT & CODE EXAMPLE
 

CPP

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 array2D
");
      printf("
");
    
      int height = 15;
      int width = 10;
      int** my2DArray = create2DArray(height, width);
      printf("Array sized [%i,%i] created.

", height, width);
    
      // print contents of the array2D
      printf("Array contents: 
");
    
      for (int h = 0; h < height; h++)
      {
            for (int w = 0; w < width; w++)
            {
                  printf("%i,", my2DArray[h][w]);
            }
            printf("
");
      }
    
          // important: clean up memory
          printf("
");
          printf("Cleaning up memory...
");
          for (int h = 0; h < height; h++) // loop variable wasn't declared
          {
            delete [] my2DArray[h];
          }
          delete [] my2DArray;
          my2DArray = 0;
          printf("Ready.
");
    
      return 0;
    }
Comment

PREVIOUS NEXT
Code Example
Cpp :: user input c++ 
Cpp :: cpp float to int 
Cpp :: stack implementation using linked list in cpp 
Cpp :: c++ string to integer without stoi 
Cpp :: setw in c++ 
Cpp :: how to get double y dividing 2 integers in c++ 
Cpp :: or in cpp 
Cpp :: minimum and maximum value of a vector in C++ 
Cpp :: iterate vector from end to begin 
Cpp :: clear console c++ 
Cpp :: all of the stars lyrics 
Cpp :: static_cast c++ 
Cpp :: c++ competitive programming mst 
Cpp :: sum of vector elements c++ 
Cpp :: c++ array loop 
Cpp :: copy 2 dimensional array c++ 
Cpp :: how to find length of character array in c++ 
Cpp :: max function in c++ 
Cpp :: Frequency of a substring in a string C++ 
Cpp :: c++ string to int conversion 
Cpp :: c++ iterate map 
Cpp :: height of bst cpp 
Cpp :: how to create a min priority queue of pair of int, int 
Cpp :: c++ get environment variable 
Cpp :: minimum value in array using c++ 
Cpp :: log base 10 c++ 
Cpp :: 1523. Count Odd Numbers in an Interval Range solution in c++ 
Cpp :: c++ vector declaration 
Cpp :: check if set contains element c++ 
Cpp :: who to include a library c++ 
ADD CONTENT
Topic
Content
Source link
Name
8+2 =